Possible Duplicate:
Addition of two chars produces int
Given the following C++ code:
unsigned char a = 200;
unsigned char b = 100;
unsigned char c = (a + b) / 2;
The output is 150 as logically expected, however shouldn’t there be an integer overflow in the expression (a + b)?
Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn’t rely on in terms of integer promotion and overflow.
Neither C++ not C perform arithmetical computations withing “smaller” integer types like,
charandshort. These types almost always get promoted tointbefore any further computations begin. So, your expression is really evaluated asP.S. On some exotic platform where the range of
intdoes not cover the range ofunsigned char, the typeunsigned intwill be used as target type for promotion.