为什么此代码存在运行时错误?

Why is there a run time error for this code?

本文关键字:运行时错误 存在 代码 为什么      更新时间:2023-10-16

如果我在if循环中i++评论,while循环将运行并至少打印0,1,2,3。但是,相反,它会输出 Shell 中超出C++运行时。我不明白为什么?

#include <iostream>
using namespace std;

int main() {
int i = 0;
while (i < 10) {
if (i == 4) {
//   i++;
continue;
}
cout << i << "n";
i++;
} 
return 0;
}

continue 语句会导致跳跃,就像通过转到循环体的末尾一样,跳过i++导致无限循环,因为我保持 4。

使用break而不是continue,那么机器就会明白循环需要在i == 4处退出。

执行以下操作:

#include <iostream>
int main(void) {
int i = 0;
while (i < 10) {
if (i == 4) break;
std::cout << i << std::endl;
i++;
}

return 0;
}

另外,请注意,While 循环不会迭代到 10,因为我们在满足i == 4时设置了 break 语句。