无符号位域的类型:int 或 unsigned int

发布于 2024-11-06 22:27:18 字数 823 浏览 0 评论 0原文

C99 标准第 6.3.1.1 节包含:

以下内容可用于 表达式,无论 int 或 可以使用unsigned int

[...] _Bool 类型的位字段, intsigned intunsigned 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 an int or
unsigned int may be used:

[...] A bit-field of type _Bool,
int, signed int, or unsigned
int
.

If an int can represent all values
of the original type, the value is
converted to an int; otherwise, it
is converted to an unsigned 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可是我不能没有你 2024-11-13 22:27:18

标准委员会似乎已经发现了这种歧义,因为当前草案澄清了这句话:

如果一个int可以表示所有的值
原始类型(受限制)
宽度(对于位字段)、值
转换为 int;

It seems that this ambiguity has already been detected by the standards committee since the current draft clarifies that sentence:

If an int can represent all values of
the original type (as restricted by
the width, for a bit-field), the value
is converted to an int;

踏雪无痕 2024-11-13 22:27:18

我的阅读与您相同: 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文