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

weird thing in C: not zero is not equal to one

int main()
{
    int a = 2147483647; 
    int c = a + a + 2;
    printf("2a + 2 = %d, !(2a + 2) = %d, !c = %d\n", (2 * a + 2), !(a + a + 2), !c);
}

I got this when I run those codes above

2a + 2 = 0, !(2a + 2) = 0, !c = 1

a is Tmax which in binary form is 0111…111, so a + a + 2 is suposed to be 0000…0000.
I don’t understand why !(2a + 2) is not equal to 1 when (2a + 2) is actually 0, but !c is 1!!!
Please help me

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

>Solution :

Assuming an int is 32 bits, the operations you’re performing cause signed integer overflow. Doing so triggers undefined behavior. It does not necessarily wraparound.

In fact, this specific case is given as an example of undefined behavior in section 3.4.3p3 of the C standard where the term undefined behavior is defined:

An example of undefined behavior is the behavior on integer overflow

You’ve encountered one of the stranger ways that undefined behavior can manifest itself, where seemingly identical operations behave differently. Undefined behavior means that no guarantees are made about what your program will do.

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