-7

I cant figure out how the following loop can ever end:

for(int i;i<i+1;i++)
blalasaadri
  • 5,990
  • 5
  • 38
  • 58
EzioPC
  • 35
  • 4

2 Answers2

7

Overflowing a signed integer is undefined behaviour. Which manifests itself either in loop terminating or not.

Also, you do not initialize i but access its value which is undefined behaviour as well.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
2

signed integers are implemented using twos complement arithmetic, this has negative values when the top bit is set . When you do a the maximum positive value +1 you get the maximum negative value at which point the condition becomes false. This isn't defined by the C standard, but is very likely to be the case unless you are on odd hardware.

James Snook
  • 4,063
  • 2
  • 18
  • 30
  • ... or you have a good compiler that optimizes this code by throwing away the condition check at all (or even the whole code :) due to undefined behavior which the code exposes. – user396672 Sep 11 '14 at 15:55