Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of unsigned bit-fields: int or unsigned int

Tags:

c

c99

bit-fields

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)

like image 789
Pascal Cuoq Avatar asked May 12 '11 11:05

Pascal Cuoq


2 Answers

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;

like image 141
Jens Gustedt Avatar answered Sep 21 '22 06:09

Jens Gustedt


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

like image 25
AProgrammer Avatar answered Sep 22 '22 06:09

AProgrammer