runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
当我在参数 n 的值为 2147483647 时执行下面的代码时,出现错误(运行时错误:有符号整数溢出:2147483647 + 1 无法在类型 'int'[=14 中表示=]) 来自 if 阶段。但是打印了“INT_MAX”。你能解释一下为什么我会收到这个错误吗?
class Solution {
public:
int myFunct(int n) {
if (n == INT_MAX) cout << "INT_MAX" << endl;
return 0;
}
};
来自提供的片段:
#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);
|
当我在参数 n 的值为 2147483647 时执行下面的代码时,出现错误(运行时错误:有符号整数溢出:2147483647 + 1 无法在类型 'int'[=14 中表示=]) 来自 if 阶段。但是打印了“INT_MAX”。你能解释一下为什么我会收到这个错误吗?
class Solution {
public:
int myFunct(int n) {
if (n == INT_MAX) cout << "INT_MAX" << endl;
return 0;
}
};
来自提供的片段:
#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);
|