1

Please check the following snippet:

  unsigned char a = 100;
  unsigned char b = 100;
  unsigned char c = 100;
  unsigned short x = a * b + c;

I expected this would overflow and the calculation would be done in 8-bit type unsigned char (not in 16-bit unsigned short), exceeding the value range of unsigned char. But it doesn't.

Why does the calculation not overflow in C and C++?

Silicomancer
  • 8,604
  • 10
  • 63
  • 130
  • 8
    Because the integral types get promoted to `int` before the calculation? http://en.cppreference.com/w/cpp/language/operator_arithmetic – UnholySheep Mar 13 '18 at 09:14

1 Answers1

8

[...] arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

http://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion

So your code behaves like this:

unsigned char a = (unsigned char)100;
unsigned char b = (unsigned char)100;
unsigned char c = (unsigned char)100;
unsigned short x = (unsigned short)((int)a * (int)b + (int)c);
Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46