未命名的位域是否具有定义明确的语义? [英] Do unnamed bit-fields have well-defined semantics?

查看:57
本文介绍了未命名的位域是否具有定义明确的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否可以正常正常终止?

Is the following code guaranteed to terminate normally and successfully?

#include <assert.h>

struct foo_s {
    union {
        struct {
            unsigned a : 10;
            unsigned   : 6;
        };
        struct {
            unsigned   : 10;
            unsigned b : 6;
        };
        struct {
            unsigned   : 10;
            unsigned c : 6;
        };
    };
};

int main () {
    struct foo_s f;
    f.a = 0;
    f.b = 1;
    assert(f.a == 0);
    return 0;
}

在回答不同的问题时,提出了一种可能性,即将结构中的命名位分配给包含未命名的位字段可能会导致将任意数据写入那些位. C.11§ 6.7.2.1¶ 12状态:

While answering a different question, the possibility was raised that assignment to a named bit-field in a structure that also contains an unnamed bit-field may cause arbitrary data to be written to those bits. C.11 §6.7.2.1 ¶12 states:

没有声明符但只有一个冒号和一个宽度的位域声明表示一个 未命名的位字段.

A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.

我的理解是,未命名的位域只是常规的位域,唯一的区别是这些位中的值不能直接通过名称获得.是否可以通过使用假设"逻辑从该实现中推断并在这些位中分配任意数据?

My reading of this is that an unnamed bit-field is just a regular bit-field, with the only difference being the value in those bits cannot be obtained directly by name. Is an implementation allowed to extrapolate from that using "as-if" logic and assign arbitrary data in those bits?

推荐答案

是的,我认为一种实现可以将任意位写入未命名的位字段.我认为脚注126仅说明了为什么引入了宽度大于0的未命名位域的意图:

Yes, I think an implementation may write arbitrary bits to an unnamed bit field. I think footnote 126 merely states the intention why unnamed bitfields of width larger than 0 were introduced:

未命名的位域结构成员可用于填充到 符合外部施加的布局.

An unnamed bit-field structure member is useful for padding to conform to externally imposed layouts.

因此,基本上未命名的位域具有与填充位相同的语义.您只是不能依靠它们的内容.

So basically unnamed bit-fields have the same semantic as padding bits. You just can't rely upon their contents.

允许实现在写入相邻的命名位字段a时基本上忽略未命名的位字段,从而大大简化了对该字段a的处理.无需读取未命名字段的当前值,并且可以一次完成原子操作.就像可能包含在结构中的填充位一样.

Allowing the implementation to basically ignore an unnamed bit-field when writing to an adjacent named bit-field a greatly eases the handling of that field a. The current value of the unnamed field doesn't have to be read and the write can be done atomically in one go. Just as for padding bits that might be contained in the structure.

这篇关于未命名的位域是否具有定义明确的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆