struct S {
char a;
int b:5,
c:11,
:0,
d:8;
struct {int ee:8;} e;
};
int main(void) {
S s;
std::cout << sizeof(s) << std::endl;
return 0;
}
the output is 12 (64bit OS). Why is that? b and c are neighbors and will be placed in the same int, then d is placed in a different int (because of zero width bitfield) and nested structs are also placed in a different memory location. So I think sizeof must be 13 but I'm at a loss and would appreciate an explanation. Thanks!
based on what g++, clang++, intel, and oracle seem to agree to when compiling this struct (microsoft differs)
S.a takes the byte #1 (naturally)
S.b takes part of byte #2
S.c takes part of byte #2 and the whole byte #3
byte #4 is left unused because we're skipping to the next whole int (bytes 5,6,7,8)
S.d takes byte #5
bytes #6, #7, #8 are unused because we're skipping to the next whole int for member struct
S.e.ee takes byte #9
bytes #10, #11, #12 are unused (and belong to S.e whose sizeof is 4)
(microsoft inserts three more padding bytes after S.a, placing S.b at the start of an int boundary, and because of that it has to skip 2 bytes instead of 1 at :0, making the total sizeof 16)
@Cubbi Thank you for the explanation. So S.a is stored in the same int that contains the bits for S.b and S.c. That would explain why deleting S.a from the struct and then recompiling would give the same size as before. Initially I thought the size would be computed like so: