gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:33:37 25 4
gpt4 key购买 nike

来自 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/52646507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com