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:

https://codeeval.dev/gist/c9180850c175861c14291f47c529282f

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.

https://codeeval.dev/gist/dd1676d3d076c48ae0d2fafa375804e8

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);