无符号位域的类型:int 或 unsigned int
C99 标准第 6.3.1.1 节包含:
以下内容可用于 表达式,无论
int
或 可以使用unsigned int
:[...]
_Bool
类型的位字段,int
、signed int
或unsigned int
.如果一个
int
可以代表所有值 原始类型的值为 转换为int
;否则,它 转换为unsigned int
。
在我看来,这意味着 unsigned int
位域被提升为 int
,除非无符号位域的宽度等于 的宽度>int
,在这种情况下,最后一个短语适用。
我有以下程序:
struct S { unsigned f:32; } x = { 28349};
unsigned short us = 0xDC23L;
main(){
int r = (x.f ^ ((short)-87)) >= us;
printf("%d\n", r);
return r;
}
以及两个执行该程序的系统(int
在两个系统上都是 32 位)。一个系统说这个程序打印 1,另一个系统说它打印 0。我的问题是,我应该针对这两个系统中的哪一个系统提交错误报告? (由于上面的摘录,我倾向于针对打印 0 的系统提交报告)
Section 6.3.1.1 of the C99 standard contains:
The following may be used in an
expression wherever anint
orunsigned int
may be used:[...] A bit-field of type
_Bool
,int
,signed int
, orunsigned
.
intIf an
int
can represent all values
of the original type, the value is
converted to anint
; otherwise, it
is converted to anunsigned int
.
It seems to me that this implies that unsigned int
bit-fields are promoted to int
, except when the width of the unsigned bit-field is equal to the width of int
, in which case the last phrase applies.
I have the following program:
struct S { unsigned f:32; } x = { 28349};
unsigned short us = 0xDC23L;
main(){
int r = (x.f ^ ((short)-87)) >= us;
printf("%d\n", r);
return r;
}
And two systems to execute this program (int
is 32-bit on both systems). One system says this program prints 1, and the other says that it prints 0. My question is, against which of the two systems should I file a bug report? (I am leaning towards filing the report against the system that prints 0, because of the excerpt above)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准委员会似乎已经发现了这种歧义,因为当前草案澄清了这句话:
It seems that this ambiguity has already been detected by the standards committee since the current draft clarifies that sentence:
我的阅读与您相同: int 大小的无符号位域应具有 unsigned int 作为类型,小于 int 则应具有有符号 int 类型。
我访问的编译器(x86 上的 gcc、Sparc 上的 Sun CC、POWER 上的 IBM xlC)具有与此读数匹配的行为(在程序中打印 1,如果位字段减少到 31 位或进行签名,则打印 0)。
My reading is the same as you: an unsigned bitfield of the size of an int should have unsigned int as type, smaller than an int it should have signed int type.
The compilers I've access (gcc on x86, Sun CC on Sparc, IBM xlC on POWER) have a behavior matching this reading (printing 1 in your program, printing 0 if the bitfield is reduced to 31 bits or made signed).