Namespaces
Variants

do - while loop

From 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 statement while ( expression );
attr - (since 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 문서 참조: do-while