Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading