0

So, i was trying this piece of code. It has no output or any warning messages. i am wondering what does the gcc compiler do underneath?

int k;
for(k=INT_MAX; k< LONG_MAX; k++){
    printf("%d\n",k);
}
Chaos
  • 307
  • 1
  • 4
  • 13

2 Answers2

2

k is a variable of type "int". INT_MAX is the largest positive integer value that can be assigned to a signed int. If you are using a compiler implementation in which "long" and "int" are the same size, then "k < LONG_MAX" will never be true, and the code will never print anything. If "long" is larger than "int" in your compiler implementation, however, incrementing k will overflow, invoking Undefined Behavior*. If this doesn't result in a trap or other signal, the typical effect will be that the value wraps to negative (giving it the value of 0 - MAX_INT - 1). So, the first time through the loop, the code will print the value of INT_MAX, k will compare less than LONG_MAX, and k++ will set the value of k to 0 - INT_MAX - 1. The second time through, the code will print that, k will of course compare smaller than LONG_MAX, and k++ will set the value of k to 0 - INT_MAX. And so on, and so forth, looping infinitely. (Until you hit CTRL-C, of course.)

*Undefined Behavior: Bad. See https://www.securecoding.cert.org/confluence/display/seccode/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow (among many other places) for why it might be desirable to avoid this.

This isn't my real name
  • 4,869
  • 3
  • 17
  • 30
0

LONG_MAX will overflow as if it were an integer. Clearly this overflown value will not be greater than the maximum possible INT value, and so the initial check will fail. Therefore, nothing is printed.

I don't think the gcc compiler will make any particularly interesting changes in this case.

user2309462
  • 126
  • 8
  • 1
    What do you mean "LONG_MAX will overflow"? LONG_MAX is a compile-time constant, and cannot be modified. – This isn't my real name Apr 23 '13 at 03:50
  • 1
    This answer is incorrect. There will be no overflow at `LONG_MAX` because nothing in that expression forces `LONG_MAX` to be converted to `int`. On the contrary, `k` will be promoted to `long` and compare to `LONG_MAX`, always returning `true` if `long` is larger than `int`. Incrementing `k` will then cause undefined behaviour, because signed integer overflow that results from arithmetic operations is undefined behaviour. – jogojapan Apr 23 '13 at 03:58