3

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.

ABu
  • 10,423
  • 6
  • 52
  • 103
  • [INT02-C. Understand integer conversion rules](https://wiki.sei.cmu.edu/confluence/display/c/INT02-C.+Understand+integer+conversion+rules) – Swordfish May 05 '19 at 15:09

2 Answers2

5

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;
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
3

The expression v - '0' * (signed char)n is grouped as v - ('0' * (signed char)n)

Both arguments '0' and (signed char)n are converted to int types prior to the multiplication. There is nothing you can do to stop that.

That total is subtracted from v which is also promoted to an int.

This yields -261 on a platform with ASCII encoding.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483