Rear gasket in internal structure

Compilers typically insert lazy padding on structures to satisfy alignment constraints when used in arrays:

// Size 4, alignment 2 struct A { uint16_t x; uint8_t y; // Padding 1 byte }; // Size 6, alignment 2 struct B { struct A xy; uint8_t z; // Padding 1 byte }; 

Now consider a combination of them using the internal structure:

 struct AB { struct { uint16_t x; uint8_t y; } xy; uint8_t z; }; 

The following can fit in 4 bytes without violating alignment restrictions. In addition, xy internal structure does not have a type that could be used elsewhere, so it does not require scrolling to scroll.

The disadvantage is that the xy member will not be compatible with struct A , but there is no reason that it should be the same as it is in the definitions of different types.

Is the compiler allowed to optimize this size?

Or, in other words, does the standard require that 2 structures with equal members always result in equal distribution?

+5
source share
1 answer

The answer is probably defined by the concept of compatible types. If t1 and t2 are compatible types, a pointer to t1 can be used to access the memory set using type t2 .

In the C11 standard:

6.2.7 Compatible type and composite type

  • ... In addition, two structures, associations, or listed types declared in separate translation units are compatible if their tags and members satisfy the following requirements: if declared by a tag, the other must be declared with the same tag . If both of them are filled in anywhere in their respective translation units, the following additional requirements apply: there must be a one-to-one correspondence between their members so that each pair of the corresponding members is declared with compatible types; if one member of a pair is declared using an alignment specifier, the other is declared with an equivalent alignment specifier; and if one member of a pair is declared with a name, another is declared with the same name ....

Two structures that do not have the same tag are not compatible types, and I do not see anything that would force them to have the same layout.

+1
source

All Articles