我有一些代码可以检查整数是否在 [−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;
}
main.cpp:93:51: warning: integer overflow in expression [-Woverflow]
if (tmp_l >= ((int32_t)-1 * (((int32_t)1<<31) - (int32_t)1) ) &&
~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
代码编译正常,我没有看到与此警告相关的运行时错误。我哪里错了?
最佳答案
Where am I going wrong?
2^31 - 1 是 32 位带符号整数可表示的最大整数。因此运行结果1 << 31
, 即 2^31 超出了可表示值的范围。
有符号溢出的行为是未定义的。
How to fix
您可以改用它:
if (tmp_l >= std::numeric_limits<int32_t>::min() + 1
&& tmp_l <= std::numeric_limits<int32_t>::max()
关于c++ - 如何修复整数溢出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55944833/