c - 是否有任何 C 实现具有无用的单位 `int` 位域?

标签 c c99 bit-fields c11

6.7.2.1p9 of n1570说:

A member of a structure or union may have any complete object type other than a variably modified type.123) In addition, a member may be declared to consist of a specified number of bits (including a sign bit, if any). Such a member is called a bit-field ;124) its width is preceded by a colon.

我是否理解正确,这表明 struct { int bit:1; 中的单个成员? 可能是一个符号位?

如果是这种情况,那么在某些实现中,这样的位字段可能存储的唯一值是 0-0,其中 -0 可能与 0 一旦存储或陷阱表示无法区分。

是否有任何实际的实现只能将一个值分配给这样的位域?

最佳答案

gcc 4.9.2 怎么样?

/* gcc -std=c11 -pedantic-errors -Wextra -Werror=all test.c */
#include <stdio.h>
#include <string.h>

struct foo {
    int bit:1;
};

int main() {
    struct foo f;
    f.bit = 0;
    f.bit = 1;

    printf("%i\n", f.bit);
    return 0;
}

编译它发出:

$ gcc -std=c11 -pedantic-errors -Wextra -Werror=all test.c
test.c: In function ‘main’: test.c:12:10: warning: overflow in
implicit constant conversion [-Woverflow]
  f.bit = 1;
          ^

运行它发出:

$ ./a.out 
-1

关于c - 是否有任何 C 实现具有无用的单位 `int` 位域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30584714/

相关文章:

c++ - 证明两个代码块在功能上是相同的?

c - sprintf() 错误 : ‘__builtin___sprintf_chk’ may write a terminating nul past the end of the destination

c - 为什么设置了 -std=c99 后 gcc 找不到 random() 接口(interface)?

c - 不能获取位域的地址

c# - 使用 c# 的 StrucLayout 和 FieldOffset 表示联合位域

c# - 在 C# 中,如何轻松地将枚举标志从一种类型映射到另一种类型?

c - While 循环不断检查用户输入的整数

c - 初始化可变长度数组

C99条件返回值

c++ - 将使用 C99 动态分配的多维数组的代码迁移到 C++