Search code examples
c++integer-promotionvalue-initialization

Value initialization from signed char to integer, premature promotion?


In this piece of code:

signed char v = -64;
int n = 4;
int x = v - '0' * (signed char)n;
std::cout << x << std::endl;

Should x be -5 or -261? In my understanding, the initializer expression has signed char type, and the type conversion should happen later, once the initializer has been calculated.

So, v - '0' * (signed char)n should be equal to -5 because that's the equivalent value of -261 in signed char valuation.

However, that piece of code prints -261.


Solution

  • chars and shorts are promoted to int when doing arithmetic. The (signed char)n cast doesn't help since the result is immediately promoted right back up to int for the multiplication.

    Here are the implicit conversions made explicit:

    int x = (int)v - (int)'0' * (int)(signed char)n;