do-while loop

suggest change

A do-while loop is very similar to a while loop, except that the condition is checked at the end of each cycle, not at the start. The loop is therefore guaranteed to execute at least once.

The following code will print 0, as the condition will evaluate to false at the end of the first iteration:

#include <iostream>
using namespace std;

auto main() -> int
{
    int i =0;
    do
    {
        std::cout << i;
        ++i;
    } while (i < 0);
    std::cout << std::endl;
}
0

Note: Do not forget the semicolon at the end of while(condition);, which is needed in the do-while construct.

In contrast to the do-while loop, the following will not print anything, because the condition evaluates to false at the beginning of the first iteration:

int i = 0;
while (i < 0)
{
    std::cout << i;
    ++i;
}
std::cout << std::endl;

Note: A while loop can be exited without the condition becoming false by using a break, goto, or return statement.

#include <iostream>
using namespace std;

auto main() -> int
{
    int i = 0;
    do
    {
        std::cout << i;
        ++i;
        if (i > 5) {
            break;
        }
    }
    while (true);
    std::cout << std::endl;
}
012345

A trivial do-while loop is also occasionally used to write macros that require their own scope (in which case the trailing semicolon is omitted from the macro definition and required to be provided by the user):

#define BAD_MACRO(x) f1(x); f2(x); f3(x);

// Only the call to f1 is protected by the condition here
if (cond) BAD_MACRO(var);

#define GOOD_MACRO(x) do { f1(x); f2(x); f3(x); } while(0)

// All calls are protected here
if (cond) GOOD_MACRO(var);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* do-while loop

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype