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

标签 c memory-alignment bit-fields

我正在学习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/

相关文章:

c++ - 在Qt中链接obj文件

c - GNU ARM 汇编程序在错误消息中给出看似无关的寄存器

c - 为什么结构必须单词对齐?

c++ - 在 C++ 中将一个 int 打包到一个位域中

c - 作者插入不需要的换行符

c - 为什么在 C11 中没有对齐的 calloc

c++ - std::string 和数据对齐

c - 用于轻松位访问的位域 union ,意外行为

c++ - 重新排序位字段神秘地改变了结构的大小

c - 我的第二大数字程序(C 程序)的输出一直不正确