Namespaces
Variants
Views
Actions

do-while loop

From cppreference.com
< cpp‎ | language

Executes a statement repeatedly, until the value of condition becomes false. The test takes place after each iteration.

Contents

[edit] Syntax

attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop

[edit] Notes

statement is always executed at least once, even if expression always yields false. If it should not execute in this case, while or for loop may be used.

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.

[edit] Keywords

do, while

[edit] Example

#include <iostream>
#include <algorithm>
#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

[edit] See also

C documentation for do-while