#include <iostream>
using namespace std;
int main()
{
cout << "sizeof(unsigned int): " << sizeof(unsigned int) << endl;
unsigned a = 1;
int i = 0;
while (a) {
cout << "a[" << i++ << "]: " << a << endl;
a <<= 1;
}
cout << "a[" << i << "]: " << a << endl;
unsigned b = 1;
unsigned c = (b << 31);
unsigned d = (b << 32);
cout << "c: " << c << endl;
cout << "d: " << d << endl;
return 0;
}/*输出http://www.compileonline.com/compile_cpp_online.php */
Compiling the source code....
$g++ main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
main.cpp: In function 'int main()':
main.cpp:19:23: warning: left shift count >= width of type [enabled by default]
Executing the program....
$demo
sizeof(unsigned int): 4
a[0]: 1
a[1]: 2
a[2]: 4
a[3]: 8
a[4]: 16
a[5]: 32
a[6]: 64
a[7]: 128
a[8]: 256
a[9]: 512
a[10]: 1024
a[11]: 2048
a[12]: 4096
a[13]: 8192
a[14]: 16384
a[15]: 32768
a[16]: 65536
a[17]: 131072
a[18]: 262144
a[19]: 524288
a[20]: 1048576
a[21]: 2097152
a[22]: 4194304
a[23]: 8388608
a[24]: 16777216
a[25]: 33554432
a[26]: 67108864
a[27]: 134217728
a[28]: 268435456
a[29]: 536870912
a[30]: 1073741824
a[31]: 2147483648
a[32]: 0
c: 2147483648
d: 1如您所见,Question>等于0。现在,为什么d不是0而是1
发布于 2013-09-14 00:21:22
这在C/C++中是未定义的行为。
该标准特别没有定义这一点,因为不同的CPU在出现这样的移位时会做不同的事情。具体地说,在32位Intel上,我认为CPU只使用移位量的低5位,其余的位被忽略。如果我没记错的话,PowerPC和64位英特尔都使用低6位,而忽略其余的位。
高级语言可能试图通过校正结果以使其在逻辑上更加一致来平滑这一点,但像C/C++这样的低级语言被设计为“接近金属”,并且希望为<<运算符生成单个位移位指令。
发布于 2013-09-14 00:24:12
b << 32是未定义的行为,因为在您的机器中b(unsigned int)的大小是32位的。
C++11§5.8移位运算符
操作数应为整型或无作用域枚举类型,并执行整型升级。结果的类型是提升的左操作数的类型。如果右操作数为负,或者大于或等于提升的左操作数的位数长度,则行为未定义。
发布于 2013-09-14 00:25:12
这是语言的一个限制。
为了帮助将<<和>>直接映射到机器语言指令,该语言继承了硬件限制,即移位计数为负或大于寄存器大小时,通常不会执行预期的操作。
例如,它也将是很好的
15 << -1意思与…相同
15 >> 1但不幸的是,事实并非如此。
https://stackoverflow.com/questions/18790923
复制相似问题