gpt4 book ai didi

c - 位字段如何与 C 中的位填充相互作用

转载 作者:行者123 更新时间:2023-12-01 16:24:04 24 4
gpt4 key购买 nike

当有填充位时,我有两个关于位字段的问题。

假设我有一个定义为的结构

struct T { 
unsigned int x: 1;
unsigned int y: 1;
};

结构体 T 仅实际使用了两位。

问题 1:这两位是否始终是底层 unsigned int 的最低有效位?或者它依赖于平台?

问题2:那些未使用的30位总是初始化为0吗? C 标准对此有何规定?

最佳答案

Question 1: are these two bits always the least significant bits of the underlying unsigned int? Or it is platform dependent?

不,它取决于系统和编译器。您永远无法假设或知道它们是 MSB 或 LSB。

Question 2: Are those unused 30 bits always initialized to 0? What do the C and C++ standards say about it?

取决于您如何初始化结构。未初始化的本地范围的结构可能在填充位/字节中包含垃圾值。使用至少一个初始值设定项集初始化的结构,即使在填充字节中也保证包含零:my_struct = { some };


来源

语言律师详细说明为什么上述作品有些复杂。

C17 6.7.9/9(强调我的)是这样说的:

Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.

这意味着我们根本不能信任填充位/字节。但上述规则有一个异常(exception)(§20 强调我的):

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

这意味着如果至少有一个初始值设定项,则适用以下静态存储初始化规则:

C17 6.7.9/10(强调我的):

If an object that has static or thread storage duration is not initialized explicitly, then: /--/

  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

关于c - 位字段如何与 C 中的位填充相互作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56216243/

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