Is right shift undefined behavior if the count is larger than the width of the type?

半世苍凉 提交于 2019-11-26 16:35:50

The draft C++ standard in section 5.8 Shift operators in paragraph 1 says(emphasis mine):

The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

So if unsigned int is 32 bits or less then this is undefined which is exactly the warning that gcc is giving you.

To explain exactly what happens: The compiler will load 34 into a register, and then your constant in another register, and perform a right shift operation with those two registers. The x86 processor performs a "shiftcount % bits" on the shift value, meaning that you get a right-shift by 2.

And since 0x0FFFFFFF (268435455 decimal) divided by 4 = 67108863, that's the result you see.

If you had a different processor, for example a PowerPC (I think), it may well give you zero.

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