为什么有些哨兵循环需要中断才能终止?C++11.
Why do some sentinel loops require break to terminate? c++11
我有一个看起来像这样的循环
int temp = 0;
int menuItem;
while (temp != -1 && temp < 5)
{
cout << "Order " << temp + 1 << ": ";
cin >> menuItem;
arrayData[temp] = menuItem;
temp++;
break;
}
当我学会使用哨兵时,我没有使用休息来学习它们......例如。
int total = 0;
int points;
int game = 1;
cout << "Enter the points for game #" << game << endl;
cin >> points;
while (points !=-1)
{
total += points;
game++;
cout << "Enter the points for game #" << game << endl;
cin >> points;
}
第二个循环继续向无穷大前进,直到输入值 -1,然后它停止而无需break;
.但是,除非包括中断,否则输入哨兵值时,我的第一个循环不会停止。
为什么?
while 语句总是重复,直到设置的条件达到 false。在您的第一个代码示例中
while (temp != -1 && temp < 5)
在这里,如果 temp
-1
或 temp
等于 5
,while 循环将退出。但是,您在代码中插入break
,这将停止或强制您的while loop
条件停止。
while (condition) {
// Some code.
// Even if the condition true, it will stop because of break.
break;
}
在第二个代码中,条件设置为
while (points !=-1)
因此,如果points
变量的值为 -1
,则while
只会停止或退出。
了解基础知识后,您将找到问题的答案,例如如果没有break;
,为什么在第一个while
它没有停止。答案是因为该while
上的条件仍然为真,因此while
再次执行。
break
总是在调用时中断循环。
但是,在您的第一个循环中,您正在阅读menuItem
,没有temp
。
因此,如果您在输入 -1 menuItem
等于 -1,则没有temp
.
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- MSVC是否支持C++11样式的属性而不是__declspec
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 终止读取时阻止的线程 c++11
- 当加入 C++11 函数的线程仍未终止时,是否可以返回?
- Node-ffi 绑定到 NULL 终止的 C 字符串数组,但得到“分段错误:11”
- C++输入超过 11 个整数时程序终止
- C++11 快速排序终止调用,没有活动异常
- 自动终止 C++11 STL 线程
- 如何在C++11中终止线程
- 在 C++11 中从外部终止线程
- 递归可变参数模板在 C++11 中由 std::tuple_size 终止
- 为什么有些哨兵循环需要中断才能终止?C++11.
- C++11 std::string::operator[]是否返回null终止的缓冲区
- C++编程分配程序以信号11终止
- C++11 的 std::string 的基础表示形式是否保证具有终止空字符?