Why is `int >> 32` not always zero?

Can someone explain to me why a correct 32 bit integer offset of 4 bytes might return non-zero in C / C ++? Why does it depend on a -O

compiler option ?

For example, this code gives 45s -O0

and 0 with parameters -O3

in gcc 4.8.3:

unsigned int x = 45; // 4 bytes
x = x >> 32;
printf("%u\n", x);

      

Why is this so?

+3


source to share


1 answer


Because this behavior is undefined: [expr.shift]

says

The behavior is undefined if the right operand is negative or greater than or equal to the bit length of the promoted left operand.

As for the specific behavior of undefined, I believe it looks like this:



  • Since -O0

    it is compiled to actually do the right shift in machine codes, and on some machines (for example, I believe x86 is), the shift functions only look at the low 5 bits of the shift amount when offsetting a 32-bit word; an offset of 32 is the same as an offset of 0.
  • With the -O3

    compiler computed the constant and just put it 0

    into the program, instead of performing the calculation.

You can check the build output to see if my prediction is correct.

+22


source







All Articles