Search code examples
cbit-fields

successive unnamed field of width zero in bit-field does not change size of struct


Here is a struct.

struct {
   unsigned int a : 8;
   unsigned int   : 0;
   unsigned int f : 1;
} A;

sizeof struct A here is 8 bytes. I understand that. But now if I put one more unnamed field of width zero right next as follows,

struct {
   unsigned int a : 8;
   unsigned int   : 0;
   unsigned int   : 0;
   unsigned int f : 1;
} A;

Now, sizeof struct A remains 8 bytes. When I see reference, it says that using an unnamed field width of 0 forces the next field to align with the next integer. So, the sizeof struct A should have been 12 bytes here. Or does putting two successive unnamed field width of 0 not have its effect as desired ?


Solution

  • C17 6.7.2.1/12:

    As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bitfield, if any, was placed.

    So : 0 means "stop packing bits in the previous bit-field". It does not mean "start packing bits in a new bit-field".

    In case of the first zero bit-field, it means that no further bits should be packed into the previous one where a : 8 was stored. If you add another zero bit-field, then the compiler still regards a : 8 as the previous one.

    As a side note, the compiler is allowed to place padding bytes pretty much wherever it pleases between bit-field members, depending on its internal size for what the standard calls "addressable storage unit". So you can never assume that the size of this struct is guaranteed to be 8 on a 32 bit system.