c - 普通 `int` 位域的符号

标签 c bit-fields

6.7.2/5 中的 C 标准说:

... it is implementation-defined whether the specifier int designates the same type as signed int or the same type as unsigned int.

x86-64 ABI 3.1.2中规定:

Bit-fields that are neither signed nor unsigned always have non-negative values. Although they may have type char, short, int, or long (which can have negative values), these bit-fields have the same range as a bit-field of the same size with the corresponding unsigned type.

因此,在下面的程序中,我希望断言能够通过(至少在 Linux 上)。

#include <assert.h>

struct S {
  int x : 3;
};

struct S s;
int main() {
  s.x = 6;
  assert(s.x == 6);
}

但它在 Clang 和 Gcc 中都失败了。为什么?

此外,Clang 会发出警告:

warning: implicit truncation from 'int' to bit-field changes value from 6 to -2

因此它的行为就好像位域被声明为signed int。如果我明确地设置它unsigned int,则警告消失并且断言通过。

最佳答案

此行为记录在 GCC manual 中:

Whether a “plain” int bit-field is treated as a signed int bit-field or as an unsigned int bit-field (C90 6.5.2, C90 6.5.2.1, C99 and C11 6.7.2, C99 and C11 6.7.2.1).

默认情况下,它被视为有符号整数,但这可以通过 -funsigned-bitfields 选项更改。

关于c - 普通 `int` 位域的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64642412/

相关文章:

c - C 中的字符串内存分配

c - 在 C 中动态分配的结构中使用位域可以吗?

c - 结构填充信息

c - fscanf 上的奇怪崩溃

c - 结构中的位域概念

python - 从整数制作 python 位数组 - 奇怪的结果!

c - malloc 位字段值到 c 中的数组

c++ - 未定义/未指定?

c - 获取相邻设备的接收信号强度

c - 指针为本地时出现段错误