do
-while
循环
来自 cppreference.cn
有条件地重复执行语句(至少一次)。
内容 |
[编辑] 语法
attr (可选) do 语句 while ( 表达式 ); |
|||||||||
attr | - | (C++11 起) 任意数量的 属性 |
表达式 | - | 一个 表达式 |
语句 | - | 一个 语句(通常是复合语句) |
[编辑] 解释
当控制到达 do 语句时,它的 语句 将会被无条件执行。
每次 语句 完成执行后,将会求值 表达式 并将其语境转换成 bool。如果结果为 true,语句 将会被再次执行。
如果循环需要在 语句 内终止,可以使用 break 语句 作为终止语句。
如果当前迭代需要在 语句 内终止,可以使用 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
[编辑] 参见
C 文档 关于 do-while
|