int main()
{
int y=2147483647;
printf("%d\n",!(~y+~y));
}
When i compile it by gcc and run it in ubuntu, the result is 0.but when i compile and run it on vs2022,the result is 1. I can not understand how did the result of 0 come about.
>Solution :
The bitwise inverse of decimal value 2147483647/0x7FFFFFFF will end up as 0x80000000. On a 2’s complement system like yours, this is equivalent to -2147483648.
-2147483648 + -2147483648 gives an arithmetic underflow of signed int, it’s undefined behavior and anything can happen. In practice, during optimization the compiler can either make the decision that ~y+~y equals zero or that it equals non-zero, it’s not well-defined.
Fix this by switching all types to int64_t/PRIi64 (#include <inttypes.h>).