9

I am wondering if x will ever reach zero in the following program.

Please consider:

int main ()
{
    int x = 1;
    while (x)
      {
        x <<= 1;
      }
    return 0;
}

Should the expected behavior of this program be exiting normally or looping forever?

1 Answers1

18

Neither (or both), it runs in undefined behavior when x overflows.

C99 spec section 6.5.7 says:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

che
  • 12,097
  • 7
  • 42
  • 71
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 2
    Thanks for the quick answer. It loops forever with gcc-4.8, but exits normally with all other compilers that I've tried (clang, icc, gcc-4.7). – user1519088 Jul 11 '12 at 21:13
  • 2
    @user1519088 there's undefined behavior for you :) – Luchian Grigore Jul 11 '12 at 21:14
  • 2
    +1, although for completeness it may be worth pointing out the behaviour for an `unsigned int`, which would probably answer the OP's *intended* question. – Oliver Charlesworth Jul 11 '12 at 21:18
  • 2
    @user1519088: GCC is known to implement "strict signed overflow semantics", which means that cycles that are known to lead to undefined behavior might be replaced with unconditional infinite cycles. http://gcc.gnu.org/gcc-4.2/changes.html – AnT stands with Russia Jul 11 '12 at 21:20
  • @user1519088 Here's another very similar example of this: http://stackoverflow.com/questions/7682477/gcc-fail-or-undefined-behavior – Mysticial Jul 12 '12 at 08:05