-1 c++ overflow undefined-behavior
考虑下面的代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
int sum = 0;
for (auto &it : a) {
cin >> it;
sum += it;
}
cout << sum << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
输入类似(或任何大于 INT_MAX 的值到 k 中)
5 1234567891564
1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
使程序打印
0
0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
到底发生了什么?k
我们根本不使用 的值。
实际上您的代码中没有整数溢出。从更广泛的意义上来说,它是存在的,但从更狭义的意义上来说,整数溢出会发生,例如:
int k = 1234567891564;
Run Code Online (Sandbox Code Playgroud)
实际发生的事情是在这一行中
cin >> n >> k;
Run Code Online (Sandbox Code Playgroud)
operator>>
尝试读取 aint
但失败。1234567891564
从未实际分配给k
. 当读取输入失败时0
将被赋值。因此k
结果为0
.
一旦流处于错误状态,所有后续调用也operator>>
将默默失败。在接受输入后,您应该始终检查流的状态。例如:
if (std::cin >> n) {
// input succeeded use the value
} else {
// input did not succeed.
std::cin.clear(); // reset all error flags
}
Run Code Online (Sandbox Code Playgroud)