do-while 迴圈
出自 cppreference.com
有條件地重複執行某個語句(至少執行一次)。
目錄 |
[編輯] 語法
attr (選填) do statement while ( expression ); |
|||||||||
| 屬性 | - | (C++11 起) 任意數量的 屬性 (attributes) |
| expression | - | 一個 運算式 (expression) |
| statement | - | 一個 語句 (statement)(通常為複合語句) |
[編輯] 說明
當控制流程到達 do 語句時,其 statement 會被無條件執行。
每當 statement 執行完畢,expression 都會被求值並依語境轉換為 bool。若結果為 true,則 statement 將再次執行。
若需要在 statement 內部終止迴圈,可以使用 break 語句作為終止語句。
若需要在 statement 內部終止當前迭代,可以使用 continue 語句作為捷徑。
[編輯] 註解
作為 C++ 進度保證 (forward progress guarantee) 的一部分,若一個迴圈(非 平凡無限迴圈)(自 C++26)不具備 可觀察行為 (observable behavior) 且無法終止,則其行為是 未定義的 (undefined)。編譯器被允許移除此類迴圈。
[編輯] 關鍵字
[編輯] 範例
執行此程式碼
#include <algorithm> #include <iostream> #include <string> int main() { int j = 2; do // compound statement is the loop body { j += 2; std::cout << j << ' '; } while (j < 9); std::cout << '\n'; // common situation where do-while loop is used std::string s = "aba"; std::sort(s.begin(), s.end()); do std::cout << s << '\n'; // expression statement is the loop body while (std::next_permutation(s.begin(), s.end())); }
輸出
4 6 8 10 aab aba baa
[編輯] 參見
| C 文件 關於 do-while
|