C++編程中break語句和continue語句的進修教程。本站提示廣大學習愛好者:(C++編程中break語句和continue語句的進修教程)文章只能為提供參考,不一定能成為您想要的結果。以下是C++編程中break語句和continue語句的進修教程正文
break 語句
break 語句可終止履行比來的關閉輪回或其地點前提語句。 掌握權將傳遞給該語句停止以後的語句(假如有的話)。
break;
備注
break 語句與 switch 前提語句和 do、for 和 while 輪回語句合營應用。
在 switch 語句中,break 語句將招致法式履行 switch 語句以外的下一語句。 假如沒有 break 語句,則將履行從婚配的 case 標簽到 switch 語句末尾之間的每一個語句,包含 default 子句。
在輪回中,break 語句將終止履行比來的 do、for 或 while 關閉語句。 掌握權將傳遞給終止語句以後的語句(假如有的話)。
在嵌套語句中,break 語句只終止直接包抄它的 do、for、switch 或 while 語句。 你可使用 return 或 goto 語句從較深嵌套的構造轉移掌握權。
示例
以下代碼演示若何在 for 輪回中應用 break 語句。
#include <iostream>
using namespace std;
int main()
{
// An example of a standard for loop
for (int i = 1; i < 10; i++)
{
cout << i << '\n';
if (i == 4)
break;
}
// An example of a range-based for loop
int nums []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i : nums) {
if (i == 4) {
break;
}
cout << i << '\n';
}
}
在每一個用例中:
1 2 3
以下代碼演示若何在 while 輪回和 do 輪回中應用 break。
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 10) {
if (i == 4) {
break;
}
cout << i << '\n';
i++;
}
i = 0;
do {
if (i == 4) {
break;
}
cout << i << '\n';
i++;
} while (i < 10);
}
在每一個用例中:
0 1 2 3
以下代碼演示若何在 switch 語句中應用 break。 假如你要分離處置每一個用例,則必需在每一個用例中應用 break;假如不應用 break,則履行下一用例中的代碼。
#include <iostream>
using namespace std;
enum Suit{ Diamonds, Hearts, Clubs, Spades };
int main() {
Suit hand;
. . .
// Assume that some enum value is set for hand
// In this example, each case is handled separately
switch (hand)
{
case Diamonds:
cout << "got Diamonds \n";
break;
case Hearts:
cout << "got Hearts \n";
break;
case Clubs:
cout << "got Clubs \n";
break;
case Spades:
cout << "got Spades \n";
break;
default:
cout << "didn't get card \n";
}
// In this example, Diamonds and Hearts are handled one way, and
// Clubs, Spades, and the default value are handled another way
switch (hand)
{
case Diamonds:
case Hearts:
cout << "got a red card \n";
break;
case Clubs:
case Spades:
default:
cout << "didn't get a red card \n";
}
}
continue 語句
強迫轉移對最小關閉 do、for 或 while 輪回的掌握表達式的掌握。
語法
continue;
備注
將不會履行以後迭代中的一切殘剩語句。肯定輪回的下一次迭代,以下所示:
在 do 或 while 輪回中,下一個迭代起首會從新盤算 do 或 while 語句的掌握表達式。
在 for 輪回中(應用語法 for(init-expr; cond-expr; loop-expr)),將履行 loop-expr 子句。然後,從新盤算 cond-expr 子句,並依據成果肯定該輪回停止照樣停止另外一個迭代。
上面的示例演示了若何應用 continue 語句跳過代碼部門並啟動輪回的下一個迭代。
// continue_statement.cpp
#include <stdio.h>
int main()
{
int i = 0;
do
{
i++;
printf_s("在持續之前\n");
continue;
printf("在持續以後,不被輸入\n");
} while (i < 3);
printf_s("在do輪回以後\n");
}
輸入:
在持續之前 在持續之前 在持續之前 在do輪回以後