Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the same equation on gcc or vs2022 have different result

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading