C 中未命名的零长度位域是什么意思?

What does an unnamed zero length bit-field mean in C?

我在C标准草案(n1570)中看到了如下例子:

$3.14 第 4 段:结构声明为:

struct 
{
        char a;
        int b:5, c:11, :0, d:8;
        struct 
        { 
            int ee:8; 
        } e;
}

那么,:0是什么意思?

我知道位域是什么,但是:0没有名字,我不明白。

:0 没有任何标识符的目的是什么?

正如您之前链接的文档所解释的那样:

A bit-field and an adjacent non-bit-field member are in separate memory locations. The same applies to two bit-fields, if one is declared inside a nested structure declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field member declaration

这是一种告诉编译器 bc can/will 位于同一内存位置而 d 必须与它们分开并且可以同时修改为b/c

首先,让我们看章节§6.7.2.1,结构和联合说明符,P11。它说,

An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. [...]

但是,以防万一,我们明确想要两个连续的位域成员,"might be"打包到一个内存位置以驻留在单独的内存位置(即,可寻址存储单元),以上是强制它的方法。

下一段,P12,提到,

A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.126) 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 bit-field, if any, was placed.

按照你的例子,这确保 :0 周围的两个位域成员将驻留在单独的内存位置(而不是在单个可寻址存储单元内,即使仍有足够的内存来打包它们合为一)。这与在两个位域之间有一个非位域成员具有类似的效果,以强制分隔内存位置。

引用 C11,章节 §3.14,NOTE 2强调我的

A bit-field and an adjacent non-bit-field member are in separate memory locations. The same applies to two bit-fields, if one is declared inside a nested structure declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field member declaration.

此外,关于用法("why it is needed"部分

[...] The bit-fields b and c cannot be concurrently modified, but b and a, for example, can be.


附录:

关于并发部分,来自NOTE 1

Two threads of execution can update and access separate memory locations without interfering with each other.

并且,从第 §5.1.2.4/P1 章开始,

Under a hosted implementation, a program can have more than one thread of execution (or thread) running concurrently. [...]

因此,根据标准,这在理论上是可行的选择。

这是一种确保位文件不合并到 单个 内存位置的方法。

例如,假设您有一个 8 位字符,但您希望确保两个 3 位字段位于不同的位置(因此可以同时修改)。为此,您可以使用:

struct xyzzy {
    int first  : 3,
               : 0,
    int second : 3;
};

而且您不必担心手动填写 space,例如 junk : 5

对于语言律师,C11 3.14 memory location /3 声明(我强调):

A bit-field and an adjacent non-bit-field member are in separate memory locations. The same applies to two bit-fields, if one is declared inside a nested structure declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field member declaration.