12431234123412341234123 12431234123412341234123 - 19 days ago 7
C Question

Can a struct be smaller than the sum of its components?

I know that the compiler may add some padding bytes in a struct. But is it possible, when the compiler sees that we never read from a variable inside a struct, that the struct will have a smaller size than the total size of the members?

struct Foo_T
{
int a;
intmax_t b;
};


void bar(void)
{
struct Foo_T foo;
foo.a=rand();
someFunction(foo.a);
//i never access foo.b, only foo.a
if(sizeof(foo)< sizeof(int)+sizeof(intmax_t))
{
//is it possible that we can end here?
}
}

Answer

No, this is prohibited by the C standard. In C11, section 6.7.2.1 contains this statement:

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. [... ] There may be unnamed padding within a structure object, but not at its beginning.

Removing members of a struct would violate the requirement that the members have addresses that increase in the order in which they are declared.