Type of unsigned bit-fields: int or unsigned int

2019-01-18 23:46发布

问题:

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



标签: c c99 bit-fields