Namespaces
Variants
Views
Actions

do-while loop

From cppreference.com
< cpp‎ | language
Revision as of 21:27, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
while
do-while
Jump statements
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
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
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

Executes a loop.

Used where code needs to be executed several times while some condition is present. the code is executed at least once.

Contents

Syntax

do Template:sparam while ( Template:sparam )

Explanation

Template:sparam shall be an expression, whose result is convertible to bool. It is evaluated after each execution of Template:sparam. The loop continues execution only if the Template:sparam evaluates to true.

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 code is executed even if 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