I was learning about undefined behaviour and stumbled upon this code without any clear explanation:
#include <stdio.h>
#include <limits.h>
int foo ( int x) {
printf ("% d\n" , x ); //2147483647
printf ("% d\n" , x+1 ); //-2147483648 overflow
return ( x+1 ) > x ; // 1 but How????
}
int main ( void ) {
printf ("% d\n" , INT_MAX ); //2147483647
printf ("% d\n" , INT_MAX+1 ); //-2147483648 overflow
printf ("% d\n" , ( INT_MAX+1 ) > INT_MAX ); //0 makes sense, since -ve < +ve
printf ("% d\n" , foo(INT_MAX) ); //1
return 0;
}
When compiling on gcc, the compiler issues a warning:
warning: integer overflow in expression of type 'int' results in '-2147483648'
So, clearly the value of INT_MAX+1
is negative, which explains why (INT_MAX+1) > INT_MAX
evaluates to 0.
But, why (or how) is (x+1) > x
evaluating to 1 for x = INT_MAX
in foo(...)
?