rus*_*381 3 c c++ undefined-behavior language-lawyer
根据这篇关于c中未定义行为优化的有趣论文,表达式(x<<n)|(x>>32-n)"当n = 0时在C中执行未定义的行为".此stackoverflow讨论确认了负整数的行为未定义,并讨论了左移值的其他一些潜在缺陷.
请考虑以下代码:
#include <stdio.h>
#include <stdint.h>
uint32_t rotl(uint32_t x, uint32_t n)
{
return (x << n) | (x >> (32 - n));
}
int main()
{
uint32_t y = rotl(10, 0);
printf("%u\n", y);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用以下参数进行编译: -O3 -std=c11 -pedantic -Wall -Wextra
10.4294967295.有趣的是,在使用c ++编译时,这仍然是正确的:gcc结果,clang结果.
因此,我的问题如下:
来自[expr.shift],强调我的:
如果右操作数为负数,或者大于或等于提升左操作数的位长度,则行为未定义.
你在做:
(x >> (32 - n))
Run Code Online (Sandbox Code Playgroud)
用n == 0,所以你右移32中的32位数字.因此,UB.
| 归档时间: |
|
| 查看次数: |
510 次 |
| 最近记录: |