Why don't I get an integer overflow when adding two chars?
Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char
and short
. These types almost always get promoted to int
before any further computations begin. So, your expression is really evaluated as
unsigned char c = ((int) a + (int) b) / 2;
P.S. On some exotic platform where the range of int
does not cover the range of unsigned char
, the type unsigned int
will be used as target type for promotion.
No, this is not an error.
The compiler always calculates at minimum of integer precision, the result will be converted back to unsigned char on assignment only.
This is in the standard.