a + b
overflows 255 back to 4 as I would expect, then c / 2
gives 2 as I expect. But then why does the last example not overflow when evaluating the same two steps?
I'm guessing the internal calculation values are stored with more bits, then only truncated down to 8 bit when doing the assignment. In that case where is the limit, it must overflow at some point?
uint8_t a = 250;
uint8_t b = 10;
uint8_t c = (a + b);
uint8_t d = c / 2;
uint8_t e = (a + b) / 2;
std::cout << unsigned(c) << ", " << unsigned(d) << ", " << unsigned(e) << "\n";
4, 2, 130
It's called integral promotion. The operations themselves are done in your CPUs native integer type, int
, which can hold numbers greater than 255. In the a+b
case the result must be stored in an uint8_t
, and that's where the truncating is done. In the last case first there is a division which is done as an int
, and the result can be perfectly stored in an uint8_t
.