語句 break 會結束執行最接近的封入循環或條件語句,其會出現。 控制會傳遞至陳述式結尾之後的陳述式 (如果有的話)。
語法
break;
備註
語句 break 會搭配條件 switch 語句和 do、 for和 while 循環語句一起使用。
switch在語句中break,語句會導致程式在語句之外switch執行下一個語句。
break如果沒有語句,則會執行從相符case卷標到語句結尾switch的每個語句,包括 default 子句。
在迴圈中 break ,語句會結束最近封入 do、 for或 while 語句的執行。 控制會傳遞到已結束之陳述式的下一個陳述式 (如果有的話)。
在巢狀語句中break,語句只會do結束立即括住它的、 forswitch或 while 語句。 您可以使用 return 或 goto 語句,從更深入的巢狀結構傳輸控件。
範例
下列程式代碼示範如何在迴圈中使用 breakfor 語句。
#include <iostream>
using namespace std;
int main()
{
// An example of a standard for loop
for (int i = 1; i < 10; i++)
{
if (i == 4) {
break;
}
cout << i << '\n';
}
// 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
1
2
3
下列程式代碼示範如何在迴圈和迴圈中使用breakwhile。do
#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
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";
}
}