Search code examples
c++integer-promotion

Unsigned and Signed Integers


If I have a compiler that uses a 2 byte short and a 4 byte int, why are the last two lines of output different for my code?

I get that x + y overflows the short type. But are the last two lines different because math has at least int precision, you can print out the large value or because z is automatically converted to an unsigned int to print it?

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

int main() {
    unsigned short x = 65'535;
    unsigned short y = 1;
    unsigned short z = x + y;
    cout << x << endl;
    cout << y << endl;
    cout << z << endl;
    cout << x + y << endl;
}

Solution

  • Note that for cout << x + y, you're printing out an int directly; For arithmetic operator, before computation their operands will be integral promotioned, so the result of x + y will be an int.

    If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion.

    On the other hand, z is unsigned short; when the result of x + y (i.e. an int) is assigned to z implicit conversion is performed (and overflow happens).