这个大小为 1 的位域在分配 1 时实际上溢出了吗?
is this bit field of size one actually overflowing when assigning 1?
我已经编写了一些我认为应该可行的带有位域的代码,但 GCC 似乎不同意。我是不是遗漏了什么或者我真的在 GCC 中发现了错误?
简化我的代码后,测试用例非常简单。我将整数文字 1
分配给大小为一位的位域:
typedef struct bitfield
{
int bit : 1;
} bitfield;
bitfield test()
{
bitfield field = {1};
return field;
}
如果我使用 GCC 6.2.1(与 5.4.0 相同)编译它,我会收到以下警告(使用 -pedantic):
gcc -fPIC test.c -pedantic -shared
test.c: In function ‘test’:
test.c:8:23: warning: overflow in implicit constant conversion [-Woverflow]
bitfield field = {1};
^
奇怪的是:当我用 -Woverflow 替换 -pedantic 时,警告消失了。
我没有收到任何 clang 警告。
对这个位域使用unsigned int
。一个 1 位有符号数只能容纳 0
和 -1
.
typedef struct bitfield
{
unsigned int bit : 1;
} bitfield;
is this bit field of size one actually overflowing when assigning 1?
也许吧。它是实现定义的。
这是 C 中的一个地方,其中 int
和 signed int/signed
可能 不同 。
unsigned int bit : 1;
可以保存值 0 或 1。
假设2的补码机...
signed int bit : 1;
可以保存值 0 或 -1
signed bit : 1;
可以保存值 0 或 -1
int bit : 1;
可以保存值 0 或 1 or 0 或 -1
Each of the comma-separated multisets (int, signed, or signed int
) designates the same type, except that for bitfields, it is implementation-defined whether the specifier int
designates the same type as signed int
or the same type as unsigned int
. C11 dr §6.7.2 5
使用 unsigned
消除歧义。
我已经编写了一些我认为应该可行的带有位域的代码,但 GCC 似乎不同意。我是不是遗漏了什么或者我真的在 GCC 中发现了错误?
简化我的代码后,测试用例非常简单。我将整数文字 1
分配给大小为一位的位域:
typedef struct bitfield
{
int bit : 1;
} bitfield;
bitfield test()
{
bitfield field = {1};
return field;
}
如果我使用 GCC 6.2.1(与 5.4.0 相同)编译它,我会收到以下警告(使用 -pedantic):
gcc -fPIC test.c -pedantic -shared
test.c: In function ‘test’:
test.c:8:23: warning: overflow in implicit constant conversion [-Woverflow]
bitfield field = {1};
^
奇怪的是:当我用 -Woverflow 替换 -pedantic 时,警告消失了。
我没有收到任何 clang 警告。
对这个位域使用unsigned int
。一个 1 位有符号数只能容纳 0
和 -1
.
typedef struct bitfield
{
unsigned int bit : 1;
} bitfield;
is this bit field of size one actually overflowing when assigning 1?
也许吧。它是实现定义的。
这是 C 中的一个地方,其中 int
和 signed int/signed
可能 不同 。
unsigned int bit : 1;
可以保存值 0 或 1。
假设2的补码机...
signed int bit : 1;
可以保存值 0 或 -1
signed bit : 1;
可以保存值 0 或 -1
int bit : 1;
可以保存值 0 或 1 or 0 或 -1
Each of the comma-separated multisets (
int, signed, or signed int
) designates the same type, except that for bitfields, it is implementation-defined whether the specifierint
designates the same type assigned int
or the same type asunsigned int
. C11 dr §6.7.2 5
使用 unsigned
消除歧义。