C++ 中的 break 與 continue
本文將演示關於如何在 C++ 中使用 break
與 continue
語句的多種方法。
使用 break
語句操作符終止迴圈
與 continue
類似的 break
語句稱為跳轉語句,用於中斷程式執行的流程。在這種情況下,利用 break
來終止 for
迴圈語句。注意,當到達 break
並執行時,程式離開迴圈體,從下一條語句- cout << item << "3"
繼續。break
必須與迭代或 switch
語句一起使用,並且它隻影響最近的迴圈或 switch
。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::for_each;
int main() {
vector<string> arr1 = {"Gull", "Hawk"};
for (auto &item : arr1) {
cout << item << " 1 " << endl;
for (const auto &item1 : arr1) {
cout << item << " 2 " << endl;
if (item == "Hawk") {
break;
}
}
cout << item << " 3 " << endl;
}
return EXIT_SUCCESS;
}
輸出:
Gull 1
Gull 2
Gull 2
Gull 3
Hawk 1
Hawk 2
Hawk 3
使用 continue
語句跳過迴圈體的一部分
continue
語句是一種語言特徵,可用於終止當前的迴圈迭代並開始執行下一次迭代。continue
只能用於 for
、while
或 do while
迴圈中。如果語句被放在多個巢狀的迴圈塊中,continue
將只中斷內部迴圈的迭代,並繼續評估條件表示式。
在下面的例子中,如果當前的 vector
元素等於 Hawk
,就會達到 continue
語句。執行完畢後,程式就會評估 for
迴圈表示式,當前 vector
中是否還有其他元素。如果為真,則執行 cout << item << 2
行,否則達到 cout << item << 3
。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::for_each;
int main() {
vector<string> arr1 = {"Gull", "Hawk"};
for (auto &item : arr1) {
cout << item << " 1 " << endl;
for (const auto &item1 : arr1) {
cout << item << " 2 " << endl;
if (item == "Hawk") {
continue;
}
}
cout << item << " 3 " << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
輸出:
Gull 1
Gull 2
Gull 2
Gull 3
Hawk 1
Hawk 2
Hawk 2
Hawk 3
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn