0Day Forums
What's the purpose of unnamed bit field at the end of structure - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: C & C++ (https://zeroday.vip/Forum-C-C)
+--- Thread: What's the purpose of unnamed bit field at the end of structure (/Thread-What-39-s-the-purpose-of-unnamed-bit-field-at-the-end-of-structure)



What's the purpose of unnamed bit field at the end of structure - kart246829 - 07-27-2023

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?


RE: What's the purpose of unnamed bit field at the end of structure - laotian599462 - 07-27-2023

> What's the purpose of it? Is it necessary?

It is used for padding. You can look at it as anonymous member which can not be referenced.

It is optional and totally dependent on your layout requirement.


RE: What's the purpose of unnamed bit field at the end of structure - whisting84089 - 07-27-2023

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