Search code examples
c++unsigned-integer

Is a negative integer summed with a greater unsigned integer promoted to unsigned int?


After getting advised to read "C++ Primer 5 ed by Stanley B. Lipman" I don't understand this:

Page 66. "Expressions Involving Unsigned Types"

unsigned u = 10;
int i = -42;
std::cout << i + i << std::endl; // prints -84
std::cout << u + i << std::endl; // if 32-bit ints, prints 4294967264

He said:

In the second expression, the int value -42 is converted to unsigned before the addition is done. Converting a negative number to unsigned behaves exactly as if we had attempted to assign that negative value to an unsigned object. The value “wraps around” as described above.

But if I do something like this:

unsigned u = 42;
int i = -10;
std::cout << u + i << std::endl; // Why the result is 32?

As you can see -10 is not converted to unsigned int. Does this mean a comparison occurs before promoting a signed integer to an unsigned integer?


Solution

  • -10 is being converted to a unsigned integer with a very large value, the reason you get a small number is that the addition wraps you back around. With 32 bit unsigned integers -10 is the same as 4294967286. When you add 42 to that you get 4294967328, but the max value is 4294967296, so we have to take 4294967328 modulo 4294967296 and we get 32.