c++bit-shiftuint8tinteger-promotion

Why does bitwise left shift promotes an uint8_t to a wider type


I was a bit messing around with uint8_t and was curious what happens when I outflow bits to the left and found that

uint8_t i = 234;

uint8_t j = (i << 1);
auto    k = (i << 1);

std::cout << (int)j << std::endl;

std::cout << k << std::endl;

prints out

212
468

and not the expected

212
212

It seems like << does promote an uint8_t too some wider integer type. Why does it do this?

Here a link where you see it in action


Solution

  • Pretty much every arithmetic operation performs what's called the usual arithmetic conversions.

    This goes back decades.

    First, integral promotions are performed.

    After that, a common type is found and conversions take place if necessary.

    (You can learn more about this process here and here.)

    The upshot is that the result of your expression is never going to be uint8_t; it's just that in the case of j you've cast it back to uint8_t, with the wraparound that consequently ensues.