Reputation: 37227
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
Upvotes: 7
Views: 170
Reputation: 34608
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.
Upvotes: 1
Reputation: 30489
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
Upvotes: 6