如何修复整数溢出警告

Cod*_*110 0 c++ integer-overflow

我有一些代码检查整数是否在[?2 ^ 31 + 1,2 ^ 31?1]。但是,在编译期间,将引发整数溢出警告。

long int tmp_l = strtol(tokens[8].c_str(),NULL,10);

if (tmp_l >= ( (int32_t)-1 * ( ((int32_t)1<<31) - (int32_t)1) ) && 
        tmp_l <= ( ((int32_t)1 << 31) - (int32_t)1) ) {

    long int in_range = tmp_l;

} else {
    cerr << "ERROR: int not in range. Expected [(-2^31)-1, (2^31)-1]. ";
    cerr << "Found: " << tmp_l << endl;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp:93:51: warning: integer overflow in expression [-Woverflow]
     if (tmp_l >= ((int32_t)-1 * (((int32_t)1<<31) - (int32_t)1) ) &&
                                  ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

代码可以正常编译,并且我还没有看到与此警告相关的运行时错误。我要去哪里错了?

eer*_*ika 5

我要去哪里错了?

2 ^ 31-1是可由32位带符号整数表示的最大整数。因此,运算结果1 << 312 ^ 31在可表示值的范围之外。

签名溢出的行为是不确定的。

怎么修

您可以改用以下方法:

if (tmp_l >= std::numeric_limits<int32_t>::min() + 1
 && tmp_l <= std::numeric_limits<int32_t>::max()
Run Code Online (Sandbox Code Playgroud)