5
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

user6323131
  • 73
  • 1
  • 7

1 Answers1

5

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.

dbush
  • 205,898
  • 23
  • 218
  • 273