Type of unsigned bit-fields: int or unsigned int

為{幸葍}努か 提交于 2019-11-27 05:58:10

问题


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)


回答1:


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;




回答2:


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).



来源:https://stackoverflow.com/questions/5977456/type-of-unsigned-bit-fields-int-or-unsigned-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!