【问题标题】:Initializing a bitfield of an anonymous struct初始化匿名结构的位域
【发布时间】:2014-07-24 15:45:26
【问题描述】:

我不确定这是否与编译相关,但我使用的编译器是 IAR 7.10.3。

我有一个如下结构:

struct A {
  struct {
    uint8_t x:1;
    uint8_t y:2;
    uint8_t z:5;
  } b;
};

并像这样初始化它:

struct A a = {
  .b = 0xFF,
};

现在当我查看内存中的结构时,只有 x 位将设置为 '1',其余的将为零。

这是它应该按照 C 标准的行为方式吗?

【问题讨论】:

  • 这类似于this最近提出的问题。
  • @this 他正在使用IAR,位域类型可以是实现定义的类型。
  • @this c99 说A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. ...注意实现定义的类型。
  • @NiklasNorin 我引用的第 17 段涵盖了这种情况:causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.
  • 顺便说一句,您的内部结构不是 anonymous 结构。 c11 将匿名结构定义为未命名且未标记的内部结构。

标签: c


【解决方案1】:
struct A a = {
  .b = 0xFF,
};

被你的编译器解析为

struct A a = {
  .b = {0xFF},
};

相当于

struct A a = {
  .b = {0xFF, 0, 0},
};

用途:

struct A a = {
  .b = {1, 3, 31},
};

将位域的所有位设置为1。或者使用带有uint8_t 和内部结构的联合并将第一个成员初始化为0xFF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2018-01-20
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多