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 loopint nums []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i : nums) { if (i == 4) { break; } cout << i << '/n'; }}
在每個用例中:
123
以下代碼演示如何在 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);}
在每個用例中:
0123
以下代碼演示如何在 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循環之后