Consider this code:
// T is *any* type
struct str_T{
T a, b;
};
I know that there's (almost always) padding between objects with different alignments because both members are of type T
. But this time there's no different alignments. Can this assertion always pass?
static_assert(sizeof(str_T) == 2 * sizeof(T));
// i.e. padding-free
No, this is not guaranteed. Compiler can always decide to pad or to not pad extra bits between struct members. (Unless overridden)
Quoting from C11 draft, 6.7.2.1 Structure and union specifiers
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. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning
No, There is no guaranteed that it's the same memory layout.
C11 6.7.2.1(p6):
a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence
The standard doesn't enforce any layouting rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With