do-while ループ
From cppreference.com
文を条件付きで繰り返し実行します(少なくとも1回は実行されます)。
目次 |
[編集] 構文
attr (optional) do statement while ( expression ); |
|||||||||
| attr | - | (C++11以降) 任意の数の属性 |
| 式 | - | 式 (expression) |
| statement | - | 文 (statement)(通常は複合文) |
[編集] 解説
制御が do 文に達すると、その statement は無条件に実行されます。
statement の実行が終了するたびに、expression が評価され、文脈的に bool 型に変換されます。結果が true の場合、statement は再度実行されます。
statement の中でループを終了する必要がある場合、終了文として break 文を使用できます。
statement の中で現在のイテレーションを終了する必要がある場合、ショートカットとして 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
[編集] 関連項目
| do-while の C言語ドキュメント
|