Why is `int >> 32` not always zero? [duplicate]

纵然是瞬间 提交于 2019-12-10 18:42:44

问题


Can someone explain me why right 32 bitwise shift of some 4 byte integer number may return not zero in C/C++ ? Why does it depend on -O option of the compiler?

For example this code gives 45 with -O0 and 0 with -O3 options in gcc 4.8.3:

unsigned int x = 45; // 4 bytes
x = x >> 32;
printf("%u\n", x);

Why it is like this?


回答1:


Because it is undefined behavior: [expr.shift] says

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.

As for the specific undefined behavior, I imagine it is as follows:

  • With -O0, it compiled to actually perform a right shift in machine code, and on some machines (e.g. I believe x86 is such), shift functions only look at the low 5 bits of the shift amount when shifting a 32-bit word; shifting by 32 is the same as shifting by 0.
  • With -O3, the compiler computed the constant itself, and just put 0 into the program rather than having it do a calculation.

You can check the assembly output to see if my prediction is right.



来源:https://stackoverflow.com/questions/31217053/why-is-int-32-not-always-zero

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