break 可以離開目前 switch、for、while、do while 區塊,並前進至區塊後下一個陳述句,在 switch 主要用來結束陳述句進行至下一個 case 的比對,在 for、while 與 do while,主要用於中斷目前的迴圈執行,如果 break 不是出現在 for、while 迴圈或 switch 之中,會發生編譯錯誤,底下是個使用 break 的 for 例子:
for(int i = 1; i < 10; i++) {
if(i == 5) {
break;
}
cout << "i = " << i << endl;
}
continue 的作用與 break 類似,使用於迴圈,不同的是 break 會結束區塊的執行,而 continue 只會當次迴圈,並跳回迴圈區塊開頭繼續下一迴圈,而不是離開迴圈,例如上面的範例會顯示 i = 1 到 4,因為當 i 等於 5 時就會執行 break 而離開迴圈,再看下面這個程式:
for(int i = 1; i < 10; i++) {
if(i == 5) {
continue;
}
cout << "i = " << i << endl;
}
這段程式會顯示 1 到 4,與 6 到 9,當 i 等於 5 時,會執行 continue 直接結束此次迴圈,這次迴圈 cout 該行並沒有被執行,然後從區塊開頭頭執行下一次迴圈,所以 5 並沒有被顯示。
goto 是個很方便,但不被建議使用的語法,濫用的話會破壞程式的架構、使得程式難以閱讀,事實上,在完全不使用 goto 的情況下,也能撰寫程式。
goto 可以在程式中任意跳躍,跳躍前必須先設定好目的地,跳躍時必須指定目的地,例如:
START:
....
....
goto START;
其中 START 就是 goto 的一個目標標籤(Label),後面使用冒號,標籤可以出現在程式的任一個地方。
一個簡單的例子是這樣的:
#include <iostream>
using namespace std;
int main() {
BEGIN:
int input = 0;
cout << "輸入一數:";
cin >> input;
if(input == 0) {
goto ERROR;
}
cout << "100 / " << input
<< " = " << 100.0 / input
<< endl;
return 0;
ERROR:
cout << "除數不可為 0" << endl;
goto BEGIN;
}
執行結果:
輸入一數:0
除數不可為 0
輸入一數:10
100 / 10 = 10
如果輸入 0,程式會跳至 ERROR 標籤然後顯示錯誤訊息,並重新跳至 BEGIN 標籤,然後再執行一次提示與輸入。
可想而知地,若隨意使用 goto,程式的邏輯馬上會變得混亂不堪,可以的話應避免使用,這個程式也可以如下撰寫:
#include <iostream>
using namespace std;
int main() {
int input;
do {
cout << "輸入一數:";
cin >> input;
if(input) {
cout << "100 / " << input
<< " = "
<< 100.0 / input
<< endl;
break;
}
cout << "除數不可為 0" << endl;
} while(true);
return 0;
}

