do
-while
迴圈
來自 cppreference.com
有條件地重複執行一條語句(至少一次)。
目錄 |
[編輯] 語法
attr (可選) do 語句 while ( 表示式 ); |
|||||||||
屬性 | - | (自 C++11 起) 任意數量的屬性 |
表示式 | - | 一個表示式 |
語句 | - | 一個語句(通常是複合語句) |
[編輯] 解釋
當控制到達 do 語句時,其語句將無條件執行。
每次語句執行完畢後,表示式將被評估並上下文轉換為 bool。如果結果為 true,則語句將再次執行。
如果需要在語句內終止迴圈,可以使用break 語句作為終止語句。
如果需要在語句內終止當前迭代,可以使用continue 語句作為快捷方式。
[編輯] 注意
作為 C++ 前向進度保證的一部分,如果一個非平凡無限迴圈(C++26 起)且沒有可觀察行為的迴圈不終止,則行為是未定義的。編譯器可以移除此類迴圈。
[編輯] 關鍵詞
[編輯] 示例
執行此程式碼
#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
|