do
-while
loop
From cppreference.com
C++
C++ language
General topics | ||||||||||||||||
Flow control | ||||||||||||||||
Conditional execution statements | ||||||||||||||||
Iteration statements (loops) | ||||||||||||||||
|
||||||||||||||||
Jump statements | ||||||||||||||||
Functions | ||||||||||||||||
Function declaration | ||||||||||||||||
Lambda function expression | ||||||||||||||||
inline specifier | ||||||||||||||||
Dynamic exception specifications (until C++17*) | ||||||||||||||||
noexcept specifier (C++11) | ||||||||||||||||
Exceptions | ||||||||||||||||
Namespaces | ||||||||||||||||
Types | ||||||||||||||||
Specifiers | ||||||||||||||||
|
||||||||||||||||
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 | ||||||||||||||||
Statements
Conditionally executes a statement repeatedly (at least once).
Syntax
attr (optional)
do
statement
while (
expression
);
|
|||||||||
attr | - | (since C++11) any number of attributes |
expression | - | an expression |
statement | - | a statement (typically a compound statement) |
Explanation
When control reaches a do statement, its statement will be executed unconditionally.
Every time statement finishes its execution, expression will be evaluated and contextually converted to bool. If the result is true, statement
If the loop needs to be terminated within statement, a break statement
If the current iteration needs to be terminated within statement, a continue statement
Notes
As part of the C++ forward progress guarantee, the behavior is undefined if a loop that is not a trivial infinite loop (since C++26) without observable behavior
Keywords
Example
Run this code
#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())); }
Output:
4 6 8 10 aab aba baa
See also
C documentation for do-while
|