首页 > 解决方案 > 在整数常量上移动会显示警告。如何清除这个?

问题描述

参考:整数常量中的后缀

unsigned long long y = 1 << 33;

结果警告:

left shift count >= width of type [-Wshift-count-overflow]

需要从上述上下文中清除两个问题:

  1. unsigned long long 类型有 64 位,为什么我们不能在其中进行左移?
  2. int 常量('1')中的移位如何工作?

标签: c

解决方案


在 C 语言中,1 是int大多数平台上的 32 位。当您尝试在将其值存储到中之前unsigned long long将其移动 33 位时,这不会很好地结束。您可以通过 2 种方式解决此问题:

  • 改为使用1ULL,这是一个unsigned long long常数:
unsigned long long y = 1ULL << 33;
  • 赋值,然后移位:
unsigned long long y = 1;
y <<= 33;

两者都是有效的,但我建议第一个,因为它更短,你可以制作yconst。


推荐阅读