This is a follow-up to this other question
I was trying to establish at compile time whether a specific implementation had added unnamed padding inside a struct. Specific implementation like gcc allow to use pragmas to control padding and alignment in structs but at the price of compatibility with other implementations. As both static_assert
and offset_of
are required by the n1570 draft for C11, I wanted to use them to see whether an implementation used padding between members.
Here is the relevant part of code (full code in referenced question):
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
...
As 6.7.2.1 Structure and union specifiers § 15 says:
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.
I assumed that if the offset of an element in the structure was the sum of the sizes of the elements declared before it, then no padding could exist between those elements and they should be consecutively allocated thus contituting an array if they were of same type.
The question is: is the above assumption wrong and it it is (what comments on the reference question let think) why?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…