Search code examples
c++integer-promotion

Automatic promotion of arithmetic operations


Please see the following code:

#include <type_traits>
int main()
{
    using T = short;
    auto x = T(1) + T(1);
    static_assert(std::is_same_v<decltype(x), T>);
}

It seems that the above static_assert fails for all of gcc, clang, and msvc and I can't see why. The assertion still fails if I change short into any of bool, char, signed char, unsigned char, and unsigned short, because for all of those cases decltype(x) is deduced to be int.

Is this the correct behavior given what's explained in https://en.cppreference.com/w/cpp/language/operator_arithmetic?


Solution

  • Yes, this promotion from short to int is required.

    From https://en.cppreference.com/w/cpp/language/operator_arithmetic:

    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.

    And from https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion (emphasis mine):

    prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

    and finally:

    signed char or signed short can be converted to int;