Namespaces
Variants
Views
Actions

do-while loop

From cppreference.com
< cpp‎ | language
Revision as of 12:03, 1 May 2013 by Cubbi (Talk | contribs)

Executes a Template:sparam repeatedly, until the value of Template:sparam becomes false. The test takes place after each iteration.

Contents

Syntax

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


Notes

Template:sparam is always executed at least once, even if Template:sparam 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.

Keywords

do, while

Example

#include <iostream>
 
int main()
{
    int i = 0;
    do i++;
    while (i < 10);
 
    std::cout << i << '\n';
 
    i = 11;
    do i = i + 10;
    while (i < 10); // the condition is false before the loop
 
    std::cout << i << '\n';
 
    int j = 2;
    do {
        j += 2;
        std::cout << j << " ";
    } while (j < 9);
}

Output:

10
21
4 6 8 10