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 语句 作为快捷方式。

注释

作为 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