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);
}
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);
}
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.
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.