gpt4 book ai didi

c++ - 算术右移给出虚假结果?

转载 作者:IT老高 更新时间:2023-10-28 12:42:14 25 4
gpt4 key购买 nike

我一定是疯了,但是我机器上的 gcc 4.7.3 给出了最荒谬的结果。这是我正在测试的确切代码:

#include <iostream>

using namespace std;

int main(){
unsigned int b = 100000;
cout << (b>>b) << endl;
b = b >> b;
cout << b << endl;
b >>= b;
cout << b << endl;
return 0;
}

现在,任何自行右移的数字都应该得到 0 (n/(2^n) == 0整数相除n>1positive/unsigned),但不知何故这是我的输出:

100000
100000
100000

我疯了吗?可能发生了什么?

最佳答案

在 C++ 中与在 C 中一样,移位仅限于移位值的大小(以位为单位)。例如,如果 unsigned int 是 32 位,则大于 31 的移位是未定义的。

在实践中,一个常见的结果是使用移位量的低5位而忽略高位;这是由于编译器生成的机器指令正是这样做的(例如 x86 上的 SHR)。

在这种情况下,移位值是 100000(十进制),恰好是二进制的 11000011010100000 - 低 5 位为零。因此,您实际上得到了 0 的转变。但是,您不应该依赖它;从技术上讲,您看到的是未定义的行为

引用资料:

对于 C,N1570第 6.5.7 节:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

对于 C++,N3690第 5.8 节“[expr.shift]”:

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.

N1570 是一个草案,与已发布的 ISO C11 标准几乎相同;自 1989 年 ANSI C 标准以来,此条款几乎相同。

N3690 是 C++ 标准的最新草案;我不确定它是否是最好的,但同样,这个子句没有改变。

关于c++ - 算术右移给出虚假结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19636539/

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