Integer promotion

Integer promotion

Hi all,

I have a problem with the following C code:

volatile unsigned char v = 0x80;
v = v >> 7;
printf ("v = %d
", v);

With any compiler, any optimization option, it always printed 1... but today I tried with icc without optimization option and it prints 255 (!).

Note that if I replace "volatile" with "register", the binary produced by icc prints 1.
There was no "volatile" qualifier in the code where I found my original bug, but I did not manage to minimize and reproduce the bug without it.

I really do not understand how the above program can print 255.
In the instruction "v = v >> 7;", v should be first promoted to "int". The int value for the unsigned char 0x80 is 0x0...080, whereas the printed result let us think that for icc it is 0xf...f80.

2nd try:
Instead of storing the result in "v", if I store the result in another unsigned char x:

volatile unsigned char v = 0x80;
volatile unsigned char x;
x = v >> 7;
printf ("x = %d
", x);

it prints 1 again !

3rd try:
If I replace 0x80 with 0x70 in the first program (the one which does v = v >> 7), it prints what we expect: 0.

So it _seems_ that because 0x80 has its highest bit set, the compiler behaves as if "v" was signed. But it is not !

Does someone has an idea about this strange behaviour ?
Thanks in advance for your help.


1 post / 0 new
For more complete information about compiler optimizations, see our Optimization Notice.