#include<stdio.h>
void main(){
int x = 0x80000000;
if((x-1)<1)
printf("True");
else
printf("False");
}
this is from csapp practice 2.44, if this is compiler's operation, how to close it?
Assuming an int
is 32 bit, the constant 0x80000000
is outside the range of an int
and has type unsigned int
. When used to initialize an int
it is converted in an implementation defined manner. For gcc, that conversion results in x
having the value -231 (whose representation happens to be 0x80000000
) which is the smallest value it can hold.
Then when you attempt to calcuate x-1
, it causes signed integer overflow which is undefined behavior. As an example of this, if I compile this code under gcc 4.8.5 with -O0
or -O1
I get "False" as output, and if I compile with -O2
or -O3
it outputs "True".
User contributions licensed under CC BY-SA 3.0