Search code examples
c++integer-promotion

C++ Arithmetic Type Conversion with unsigned & signed integers


Code:

#include<iostream>
using std::cout; using std::endl;

int main()
{
    unsigned int i = 5;
    int x = -3;

    cout << "(i + x) = " << (i + x) << endl;

    cout << "Set x to -6" << endl;
    x = -6;

    cout << "(i + x) = " << (i + x) << endl;
}

Output:

(i + x) = 2
Set x to -6
(i + x) = 4294967295

In this example, the type of the result returned by (i + x) is an unsigned integer, however, I thought that with arithmetic type conversions, the signed integer (variable "x" in this case) is supposed to be "promoted" to an unsigned integer before the operations take place. This must not be the case since the first result of (i + x) would be (5 + (2^31 - 1 - 3)) = 4294967297 and not 2. Is there something I am missing here? It seems to me that only the final result is converted to an unsigned integer, and not the initial operands.


Solution

  • Your mistake is assuming the calculation is (5 + (2^31 - 1 - 3)). The unsigned interpretation of -3 is based on a maximum value of 2^32 - 1 (UINT_MAX), not 2^31 - 1 (INT_MAX). So you're taking 2^32 - 1 - 3 (UINT_MAX - 3), adding 5, and since that exceeds UINT_MAX, it wraps right back around to 2, at least on your two's complement system with 32 bit ints.