#include<stdio.h>
int main() {
int x = 0x80000000;
printf("%i\n",(((x - 1) >> 31) & 1)); //shows 0 as output
printf("%i\n",!(((x - 1) >> 31) & 1)); //shows 0 as output(expected 1)
}
Why is this happening? As both the statements perform the same operation except the ! operator. Why do the second printf not give 1 as output? From what I know a logical not over 0 gives 1 and logical not over other numbers gives 0. Am I doing something wrong here?
What you're seeing here is a manifestation of undefined behavior caused by signed integer overflow.
Assuming a 32-byte int
using two's complement, the value 0x80000000 is outside the range of int
, so it undergoes an implementation-defined conversion. Most likely, it converts to the value -2147483648 which is the minimum value that can be held in a int
on your system.
The next thing you do in both cases is subtract 1 from this value. This is not guaranteed to wrap around. This is considered overflow and is undefined behavior. This is why you see the results you're seeing. Once you have undefined behavior, there are no guarantees what the program will do.
User contributions licensed under CC BY-SA 3.0