Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of unnamed bit field at the end of structure

I am learning C. In C Primer Plus, I saw an bit field example as follows:

struct box_props {
    bool opaque               : 1;
    unsigned int fill_color   : 3;
    unsigned int              : 4;
    bool show_border          : 1;
    unsigned int border_color : 3;
    unsigned int border_style : 2;
    unsigned int              : 2;
};

I do understand the 4-bit unnamed bit field in the middle is used for letting the following bits start at a new byte. However, I don't understand why there is another unnamed bit field at the end of the structure. What's the purpose of it? Is it necessary?

like image 899
Naitree Avatar asked Mar 04 '15 11:03

Naitree


1 Answers

Is it necessary?

Nope, it's optional.

What's the purpose of it?

Here's what the standard says in §9.6.2, C++11 (draft N3337, emphasis mine):

A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. — end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.

So it's a hint to the compiler that summing up all the members of the struct leads to 2 octects and thus is done hoping the compiler would make the struct 2 octects long. However, as per the standard there's no such requirement. Here's the excerpt from the previous point, §9.6.1:

extra bits are used as padding bits and do not participate in the value representation of the bit-field. Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.

Hence the standard does not guarantee any further than this regarding the size or alignment of a struct/class using bit-fields.

like image 129
legends2k Avatar answered Oct 21 '22 03:10

legends2k