名前空間
変種
操作

do-while ループ

From cppreference.com
< cpp‎ | language
 
 
C++言語
全般
フロー制御
条件実行文
if
繰り返し文 (ループ)
for
範囲for (C++11)
while
do-while
ジャンプ文
関数
関数宣言
ラムダ式
inline指定子
動的例外仕様 (C++17まで*)
noexcept指定子 (C++11)
例外
名前空間
指定子
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点数
文字 - 文字列 - nullptr (C++11)
ユーザー定義 (C++11)
ユーティリティ
属性 (C++11)
typedef宣言
型エイリアス宣言 (C++11)
キャスト
メモリ確保
クラス
クラス固有の関数プロパティ
explicit (C++11)
static

特殊メンバ関数
テンプレート
その他
 
 

文を条件付きで繰り返し実行します(少なくとも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以降)観測可能な振る舞いのないループが停止しない場合、その振る舞いは未定義です。コンパイラはそのようなループを削除することが許可されています。

[編集] キーワード

do, while

[編集]

#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

[編集] 関連項目

English 日本語 中文(简体) 中文(繁體)