Signed-Unsigned addition behaving unexpectedly

Viewed 54

I've learned that when performing arithmetic on a signed and unsigned integers, the signed integer will be promoted to unsigned.

Based on that, I can't explain the behavior of this:

unsigned int u = 1000;
signed int i = -1;

std::cout << i + u << std::endl;

When I run this code, I get 999. I was expecting that i would be converted to unsigned, turning that -1 value to 4294967295.

2 Answers

Actually it is. Signed -1 is really converted to unsigned 4294967295. But unsigned 1000 + unsigned 4294967295 is 4294968295 which is 999 after the out-of-range bits are truncated. Adding (or subtracting) signed numbers in two's complement representation has this funny behavior that it actually does not matter if you do addition in "signed" or "unsigned" mode (there is difference only in the detection of overflow - which is not accessible by C/C++).

Maybe it was better to test the following code before you asked the question:

unsigned int u = 0;
signed int i = -1;

std::cout << i + u << std::endl; // Outputs `4294967295`

So it is exactly what you are expecting. But adding value 1000 to it would cause another overflow, so you're seeing 999.

Related