【发布时间】:2020-10-02 17:47:56
【问题描述】:
下面的代码在编译时会抛出由第 9 行引起的警告:
警告:移位计数 >= 类型 [-Wshift-count-overflow] 的宽度
但是,第 8 行并没有发出类似的警告,即使 k == 32(我相信)。我很好奇为什么会发生这种行为?我正在使用gcc 编译器系统。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int bit_shift(unsigned x, int i){
int k = i * 8;
unsigned n = x << k; /* line 8 */
unsigned m = x << 32; /* line 9 */
return 0;
}
int main(){
bit_shift(0x12345678, 4);
return 0;
}
【问题讨论】:
-
编译器不会通过只看到函数
bit_shift知道k >= 32。检查它的调用对于编译器来说可能是太多的工作。 -
x << 32是 UB,移位计数的范围仅为 0-31(至少在unsigned为 32 位的平台上)
标签: c compilation bit compiler-warnings bit-shift