c++ - C++ 中右移的未定义行为

标签 c++ bit-shift

来自 cppreference.com:

For unsigned a and for signed a with nonnegative values, the value of a >> b is the integer part of a/2b . For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).

In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.

如果右操作数大于或等于提升的左操作数中的位数,为什么会出现未定义的行为?
在我看来,结果应该是 0(至少对于无符号/正整数)...

特别是,对于 g++(版本 4.8.4,Ubuntu):

unsigned int x = 1;
cout << (x >> 16 >> 16) << " " << (x >> 32) << endl;

给出:0 1

最佳答案

C++ 的目标之一是允许快速、高效的代码,“接近硬件”。在大多数硬件上,整数右移或左移可以通过单个操作码来实现。问题是,在这种情况下,不同的 CPU 有不同的行为,即移位幅度大于位数。

因此,如果 C++ 强制执行移位操作的特定行为,则在为操作码行为不符合所有标准要求的 CPU 生成代码时,编译器将需要插入检查和逻辑以确保结果符合所有情况下的标准。几乎所有内置移位运算符的使用都需要发生这种情况,除非优化器可以证明极端情况实际上不会发生。添加的检查和逻辑可能会减慢程序速度。

关于c++ - C++ 中右移的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783259/

相关文章:

c++ - CUDA 中的 float(0.0) 与 0.0f

c++ - 访问修饰符在继承中的不同行为取决于 "this"关键字和模板或缺少它们

assembly - 8086 汇编中的大二进制移位?

c++ - 如何获得第n位值

c++ - OpenScenegraph 示例代码问题

android - Libcurl Certificate Pinning 在 iPhone 上工作但在 Android 上不工作

C++编译时/运行时选项和参数,如何处理?

c - 左移操作。这个计算正确吗?

c - 如何在没有 stdlib 的情况下将多个数字合并为一个数字,例如 4,0,0 合并为 400

c - 在 C 中将 int 移位 32 次