Namespaces
Variants

do - while loop

From ja.cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
while
do-while
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

条件付きで文を繰り返し実行します(少なくとも一度は実行されます)。

目次

構文

attr  (オプション) do 文 while ( 式 );
attr - (C++11以降) 任意の数の 属性
expression - 任意の 式
statement - 任意の 文 (通常は複合文)

説明

制御が do 文に到達すると、その statement は無条件に実行されます。

実行が完了するたびに、 statement が expression を評価し、文脈的に bool に変換します。結果が true の場合、 statement が再度実行されます。

ループを statement 内で終了させる必要がある場合、 break statement を終了文として使用できます。

現在の反復処理をstatement内で終了させる必要がある場合、 continue statement をショートカットとして使用できます。

注記

C++の 前方進行保証 の一部として、 自明な無限ループではない 自明な無限ループ (C++26以降) ループが 観測可能な動作 を持たずに終了しない場合、その動作は 未定義 です。コンパイラはそのようなループを削除することが許可されています。

キーワード

do 、 while

例

#include <algorithm>
#include <iostream>
#include <string>
int main()
{
    int j = 2;
    do // 複合文がループ本体
    {
        j += 2;
        std::cout << j << ' ';
    }
    while (j < 9);
    std::cout << '\n';
    // do-whileループが使用される一般的な状況
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do std::cout << s << '\n'; // 式文がループ本体
    while (std::next_permutation(s.begin(), s.end()));
}

出力:

4 6 8 10
aab
aba
baa

関連項目

C documentation for do-while