使用 gcc 进行按位移位的意外行为
我有一个这样的测试程序:
int main()
{
unsigned n = 32;
printf("ans << 32 = 0x%X\n", (~0x0U) << 32);
printf("ans >> 32 = 0x%X\n", (~0x0U) >> 32);
printf("ans << n(32) = 0x%X\n", (~0x0U) << n);
printf("ans >> n(32) = 0x%X\n", (~0x0U) >> n);
return 0;
}
它产生以下输出:
ans << 32 = 0x0 ... (1)
ans >> 32 = 0x0 ... (2)
ans << n(32) = 0xFFFFFFFF ... (3)
ans >> n(32) = 0xFFFFFFFF ... (4)
我期望 (1) 和 (3) 相同,以及 (2) 和 (4) 相同。
使用 gcc 版本:gcc.real (Ubuntu 4.4.1-4ubuntu9) 4.4.1
发生了什么?
I have a test program like this:
int main()
{
unsigned n = 32;
printf("ans << 32 = 0x%X\n", (~0x0U) << 32);
printf("ans >> 32 = 0x%X\n", (~0x0U) >> 32);
printf("ans << n(32) = 0x%X\n", (~0x0U) << n);
printf("ans >> n(32) = 0x%X\n", (~0x0U) >> n);
return 0;
}
It produces the following output:
ans << 32 = 0x0 ... (1)
ans >> 32 = 0x0 ... (2)
ans << n(32) = 0xFFFFFFFF ... (3)
ans >> n(32) = 0xFFFFFFFF ... (4)
I was expecting (1) and (3) to be the same, as well as (2) and (4) to be the same.
Using gcc version: gcc.real (Ubuntu 4.4.1-4ubuntu9) 4.4.1
What is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 C 标准,第 6.5.7.3 条:
您的编译器应该警告您这一点:
如果您查看 gcc 正在生成的 汇编代码,您会看到它是实际上在编译时计算前两个结果。简化:
Shifting by the size of the type is undefined behavior, according to the C standard, § 6.5.7.3:
Your compiler should warn you about this:
If you look at the assembler code gcc is generating, you'll see it is actually calculating the first two results at compilation time. Simplified: