6.7.2/5 中的 C 标准说:
... it is implementation-defined whether the specifier
int
designates the same type assigned int
or the same type asunsigned 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
, orlong
(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 选项更改。
block 引用>
关于c - 普通 `int` 位域的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64642412/