gpt4 book ai didi

c - 结构末尾未命名位域的用途是什么

转载 作者:太空狗 更新时间:2023-10-29 15:17:40 24 4
gpt4 key购买 nike

我正在学习C。在C Primer Plus中,我看到了一个位域示例,如下所示:

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;
};

我确实理解中间的 4 位未命名位字段用于让后续位从新字节开始。但是,我不明白为什么在结构的末尾还有另一个未命名的位域。它的目的是什么?有必要吗?

最佳答案

Is it necessary?

不,它是可选的。

What's the purpose of it?

这是标准在 §9.6.2,C++11(草案 N3337,强调我的)中所说的内容:

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.

所以这是对编译器的一个提示,将 struct 的所有成员相加得到 2 个八位字节,因此希望编译器将 struct 设为 2 个八位字节长。但是,根据标准,没有这样的要求。这是前一点 §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.

因此,对于使用位域的 struct/class 的大小或对齐方式,标准不提供任何进一步的保证。

关于c - 结构末尾未命名位域的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com