10

Consider the following code:

int i = 3 << 65;

I would expect that the result is i==0, however the actual result is i==6. With some testing I found that with the following code:

int i, s;
int a = i << s;
int b = i << (s & 31);

the values of a and b are always the same.

Does the C standard say anything about shifting more than 32 bits (the width of type int) or is this unspecified behavior?

bcmpinc
  • 3,202
  • 29
  • 36

1 Answers1

16

From my WG12/N1124 draft (not the standard, but Good Enough For Me), there's the following block in 6.5.7 Bitwise shift operators:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

So, undefined. Be careful.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • "Good Enough For Me" -- good enough for everyone, since the standard contains exactly the same language. :-) Note that you can also obtain C99 + TC3 free at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf and it too has the same language, so even if you don't have the standard itself you can be pretty sure what it says! – Jim Balter Jun 30 '12 at 01:07
  • 4
    You can also obtain a much more reader-friendly html version here: http://port70.net/~nsz/c/c99/n1256.html – R.. GitHub STOP HELPING ICE Jun 30 '12 at 01:20
  • @R.., oh, thanks, that'll be way easier to read than the PDF. :) – sarnold Jul 02 '12 at 22:11
  • @Jim: Thanks for the confirmation and link -- I can never find those links when I need them. :) – sarnold Jul 02 '12 at 22:13