【问题标题】:runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'运行时错误:有符号整数溢出:2147483647 + 1 不能以“int”类型表示
【发布时间】:2020-07-22 03:55:50
【问题描述】:

当我在参数 n 的值为 2147483647 时执行下面的代码时,我从 if 阶段得到错误(运行时错误:有符号整数溢出:2147483647 + 1 不能在类型“int”中表示)。但是会打印“INT_MAX”。你能解释一下为什么我会收到这个错误吗?

class Solution {
public:
    int myFunct(int n) {
        if (n == INT_MAX) cout << "INT_MAX" << endl;
        
        return 0;
    }
};

【问题讨论】:

  • 您使用的是什么编译器和版本?
  • 2147483647INT_MAX 的值,如果 int 是 32 位类型。表达式 2147483647 + 1 导致 32 位 int 溢出(这是 C++ 中的未定义行为)。我希望INT_MAX + 1 也一样。
  • 显示的代码无法执行,因为没有main。您收到的错误表明您有一个类似n + 1 的表达式,其中n2147483647,但代码中没有显示这样的表达式,因此在给定代码中不太可能发生错误( if (n == INT_MAX) 不是错误的来源)。
  • 请向minimal reproducible example 提供完整的可编译代码和完整的编译器输出
  • 抱歉没有解释。这段代码是在leetcode.com上运行的,所以我不用写main(),leetcode使用C++17标准。

标签: c++ runtime-error overflow


【解决方案1】:

来自提供的 sn-p:

#include <iostream>

class Solution {
public:
    int myFunct(int n) {
        if (n == INT_MAX)
            std::cout << "INT_MAX" << std::endl;

        return 0;
    }
};

int main(void) {
    Solution s;
    // Here we are passing +1 than INT_MAX value
    // (i.e. overflowing 4-bytes integer)
    s.myFunct(INT_MAX + 1);

    return 0;
}

尝试存储超出INT_MAX 限制的值将导致溢出并导致运行时出现未定义行为。 因为它是 UB,它可能对您有用,但对我们无效。

也就是说,我的 TDM-GCC 9.2.0 编译器产生了错误:

main.cpp: In function 'int main()':
main.cpp:21:23: warning: integer overflow in expression of type 'int' results in '-2147483648' [-Woverflow]
   21 |     s.myFunct(INT_MAX + 1);
      |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多