c++ - 如何修复整数溢出警告

标签 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;
}
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/

相关文章:

c++ - 卸载boost并安装另一个版本

c++ - pthread_create::无法使用类型为 'void *(*)(void *)' 的右值初始化类型为 'void *' 的参数

c++ - Unordered_map 使用指针地址作为键

c++ - c++ 中的 int(或 long long)溢出如何影响模数?

java - 为什么我在使用最大整数值时会得到荒谬的值?

c++ - 为什么候选 '=' 运算符重载被标记为 const?

c++ - 公共(public)数据成员与 Getters、Setters

c++ - 没有有用且可靠的方法来检测 C/C++ 中的整数溢出?

c++ - 整数类型转换错误?

c++ - 在 64 位可执行文件中执行 64 位计算