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

为君一笑 提交于 2019-12-11 12:13:35

问题


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


回答1:


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

This goes back decades.

First, integral promotions are performed.

  • No arithmetic operation takes uint8_t so both of your operands will always be promoted.

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

  • You can prevent this by casting the right-hand-side to the type of i but, per the above rule, that doesn't get you anything in this case.

(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.



来源:https://stackoverflow.com/questions/57609263/why-does-bitwise-left-shift-promotes-an-uint8-t-to-a-wider-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!