測試條件,條件為真時執行一或多陳述句。
if (x == 10); // 警告!多餘分號!
DoSomething(x); // 永遠執行,編譯器視為空陳述句
程式碼合法但無用,編譯器無法警告。
if (x > 10) {
cout << "The number is greater than 10" << endl;
DoSomethingWithNumber(x);
}
if (fileGood) ReadData(); // 等同 if (fileGood == true)
bool fileGood = OpenSomeFile();
if (!fileGood) ReportError(); // 邏輯非測試 false
非零值即為 true,bool 或其他型別皆適用。
if (x == 20) { DoSomething(x); }
else { DoADifferentThing(x); }
if (cond_expr_1) { true_statements_1; }
else if (cond_expr_2) { true_statements_2; }
else { false_statements; }
所有程式語言共同要素。用於陣列遍歷、重複動作、讀取檔案等。
三種迴圈:for、while、do-while。共同要素:起點、迴圈本體(通常在大括號)、終點、終止測試條件、可選 break/continue。
三參數:初始值、測試條件、遞增運算式。
for (initial; cond_expr; adjust) { statements; }
```
範例:
for (int i = 0; i < 10; i++) {
cout << "This is iteration " << i << endl;
}
僅有測試條件,每次迴圈開始檢查。條件為 true 持續執行。
int x;
while (x < 1000) {
x = DoSomeCalculation(); // 假設最終回傳 >= 1000
}
常用 bool 變數控制:
bool done = false;
while (!done) {
// some code
done = SomeFunctionReturningBool();
// more code
}
與 while 類似,兩點不同:
while 測試在迴圈開頭,do-while 測試在迴圈結尾。do-while 至少執行一次迴圈本體。
bool done = false;
do {
// some code
done = SomeFunctionReturningBool();
// more code
} while (!done);
語法:
do { statements; } while (cond_expr);
選擇 while 還是 do-while 取決於迴圈本身邏輯。