3

Possible Duplicate:
Weird behavior of right shift operator

Hello

Why both numbers from this function are printed the same? It is not a cyclic shift.

unsigned int i=0x89878685;
int main()
{
  printf("0x%x\n", i);
  printf("0x%x\n", i>>32);
}

$ ./a.out
0x89878685
0x89878685

Do all compilers work in this way?

Community
  • 1
  • 1
osgx
  • 90,338
  • 53
  • 357
  • 513

1 Answers1

10

Shifting a 32-bit integer by 32 bits is undefined behavior. The result is not predictable.

In C and C++ if the integer has N bits, you are only allowed to shift by less then N bits. If you shift N or more the behavior is undefined.

In practice, when shifting a 32-bit integer, some platforms will simply interpret the shift count as a 5-bit value (discard any bits above the lower 5), meaning that 32 will be interpreted the same way as 0. This is apparently what happens on your platform. The value is not shifted at all.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • But what do major compilers in this case? – osgx Apr 13 '11 at 14:59
  • 8
    @osgx: they whatever they want, behaviour is **undefined**. – Tony The Lion Apr 13 '11 at 15:00
  • @osgx: The compiler will most likely simply generate the plain shift instruction for CPU and forget about it. So the behavior will be defined by the behavior of the CPU shift instruction. In your case it simply ignored the shift. – AnT stands with Russia Apr 13 '11 at 15:01
  • 2
    @osgx, I suspect that the compiler takes the right-hand side of the shift operator mod 32. So in this case `i >> 32` becomes `i >> (32 % 32) == i >> 0 == i`. – JSBձոգչ Apr 13 '11 at 15:02
  • @AndreyT is probably right, actually, it's the CPU that's doing the modding, not the compiler. – JSBձոգչ Apr 13 '11 at 15:02
  • 1
    @osgx: why does it matter? If you're relying on the behavior of "major compilers" when it's undefined, your code is horribly broken. – Wooble Apr 13 '11 at 15:03
  • @Wooble: I agree fully, but I wonder if you'd agree with your own logic applied to `(-1)<<1`, which also has undefined behavior. – R.. GitHub STOP HELPING ICE Apr 13 '11 at 16:03
  • @R..: The C standards do not require implementations to specify any particular behavior when signed numbers overflow, but allows them to do so. If an implementation specifies that signed overflow will result in some particular behavior, signed overflow will not invoke Undefined Behavior on that platform. – supercat Nov 20 '13 at 18:05