0

I don't understand the following behaviour of left bitwise shifting in C:

int x=0;
int y = 2 << (x-1);
// y is now 0

With the same compiler this expression evaluates as expected:

int y = 2 << (0-1);
// y is now 1
Enrico Granata
  • 3,303
  • 18
  • 25
Sebastian S
  • 4,420
  • 4
  • 34
  • 63
  • 5
    Undefined behavior. The compiler can do anything it wants. – Falmarri Oct 10 '14 at 21:58
  • but it should be the "same kind of undefined" each time, shouldn't it? – Sebastian S Oct 10 '14 at 21:58
  • 4
    No. That's what "undefined" means. Do not expect *anything*. – Paul Roub Oct 10 '14 at 22:02
  • 1
    Nope. You can't reason about undefined behavior. The compiler can assume that what's on the right side of the shift is positive, so it can optimize or really do anything it wants. – Falmarri Oct 10 '14 at 22:02
  • Try compiling with different optimization levels and see if anything changes (it does for me). As others said, "undefined" means undefined. – Alok-- Oct 10 '14 at 22:04
  • 2
    @SebastianS not necessarily the same, because in the second case, the compiler know the value during compile time and can decide to turn the left shift into a right shift, but in the first case, if `x` is unknown at compile time, the (undefined) behavior will be platform-specific. – André Sassi Oct 10 '14 at 22:05
  • @AndréSassi Thanks, that explains it :) – Sebastian S Oct 10 '14 at 22:25

0 Answers0