为什么有些哨兵循环需要中断才能终止?C++11.

Why do some sentinel loops require break to terminate? c++11

本文关键字:终止 C++11 中断 哨兵 循环 为什么      更新时间:2023-10-16

我有一个看起来像这样的循环

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 -1temp 等于 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 .