A weird question for Tmax(0x7fffffff), why (!x) == x?

3
#include <stdio.h>
void show_case(int x) {
    printf("x + x + 2 = %d\n", x + x + 2);
    printf("!(x + x + 2) = %d\n", !(x + x + 2));
}
int main(){
    show_case(-1);  // the output is 0 & 1
    show_case(0x7fffffff); // the output is 0 & 0;
    return 0;
}

hi friends, recently I come across a very weird question when dealing with the datalab in cmu15213.

I simplified the question into the code above.

As we can see, I have implemented a show_case function which can show the (x + x + 2) and !(x + x + 2); when the argument is -1, the result is as we expected, x+x+2 = 0 and !(x+x+2) = 1.

But when I turn to 0x7fffffff, I found that x+x+2 = 0 and !(x + x + 2) = 0 which is really weird for me.

(Note : the code above was ran on my Ubuntu virtual Machine, while in my windows visual studio, it turns out the ans for 0x7fffffff is 0 & 1 which is as expected). enter image description here

c++
c
asked on Stack Overflow Jun 23, 2020 by Xikai_Yang

2 Answers

7

Assuming an int is 32 bits, 0x7fffffff is the largest value an int can store. When you then add that value to itself it results in integer overflow which is undefined behavior.

When I run this code, I get 0 and 1 for the second case. This is an example of how undefined behavior can manifest: it works differently on two different systems.

If you change the type of x to unsigned int, you'll have well defined behavior for wraparound and get 0 and 1.

answered on Stack Overflow Jun 23, 2020 by dbush
2

Because you overflow the the integer. An integer overflow is an Undefined Behaviour.

If you change the parameter to unsigned (which will wrap around) - it will behave as you want

https://godbolt.org/z/Ydp55C

answered on Stack Overflow Jun 23, 2020 by P__J__

User contributions licensed under CC BY-SA 3.0