执行1 << 40时移位计数溢出

pyt*_*152 2 c++ c++11

我对左移的以下代码行为感到困惑:意图是定义一个变量太字节TB = 1024*1024*1024*1024,这将是2**401<<40.什么是抱怨:

warning: shift count >= width of type [-Wshift-count-overflow]
    uint64_t TB = 1<<40;
                   ^ ~~
1 warning generated.
Run Code Online (Sandbox Code Playgroud)

这是在Mac(10.13.1)上编译的,其中clang-900.0.38,-std = c ++ 11.

#include <cstdint>
#include <iostream>

int main(int argc, char** argv) {

    uint64_t TB = 1<<40;
    std::cout << "TB = " << TB << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

vic*_*tcu 12

试试这段代码:

1ULL << 40

如果您需要默认值以外的常量,则常量需要限定类型.

  • 或者使用宏来匹配类型,`UINT64_C(1)<< 40`. (5认同)