为什么此代码存在运行时错误?
Why is there a run time error for this code?
如果我在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 语句。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- 运行时错误 -f1.exe 不存在或不是可执行文件
- 代码中存在无法预测的SIGSEGV(运行时错误)
- 编译容易,但存在运行时错误
- 此代码中存在运行时错误