Language[lang]

C++ do while loop: syntax, examples and do while vs while

Section
Language [lang]
Standard
C++17
Compilers
MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2, Clang 23.1 (libc++)
Published
Length
7 min read
In this answer8 clauses
  1. 1What is the syntax of a do while loop in C++?
  2. 2What is the difference between while and do while?
  3. 3When should you use a do while loop?
  4. 4How do you make a menu with a do while loop?
  5. 5Why can’t the condition see a variable declared in the body?
  6. 6How do break and continue work in a do while loop?
  7. 7What is do { } while (0) in a macro?
  8. 8While, do while or for: which loop?

Abstract

A C++ do while loop, do { ... } while (condition);, runs its body first and tests the condition after each pass, so the body runs at least once; a while loop tests first and may run zero times. Use it when the body must run before there is anything to test, such as a menu or an input check. End it with a semicolon, declare before do any variable the condition reads, and remember that continue jumps to the condition.

A line runs straight into a hatched block, then on to a blue diamond. One line leaves the diamond to the right; another rises from its top corner and curves back down into the block.
Figure 1 — The body comes first, the test after.

A do while loop in C++ runs its body first and tests its condition afterwards, so the body always runs at least once. Write do { ... } while (condition); with a semicolon at the end. A true condition repeats the body; a false one ends the loop. Use it when the first pass must come before any test: a menu, an input check.

The smallest one counts to three:

[Example 1:
#include <iostream>

int main() {
    int n = 1;
    do {
        std::cout << n << '\n';
        ++n;
    } while (n <= 3);
}

— end example]

It printed 1, 2 and 3, one per line: after the third pass n is 4, and the test ends the loop.

The samples are C++17, built with MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2 and Clang 23.1 (libc++), and all four printed the same. The loop has worked this way since C++98, so nothing here needs a newer standard; Since When lists what each one added.

What is the syntax of a do while loop in C++?

The keyword do, the body, then while, the condition in parentheses, and a semicolon. The standard’s grammar is do statement while ( expression ) ; ([stmt.iter]): the body is one statement, usually a block in braces, and the condition is any expression that converts to bool, tested after each run of the body ([stmt.do]).

The semicolon is part of the statement. Leave it out, and the program does not compile:

[Example 2:
do {
    std::cout << n << '\n';
    ++n;
} while (n <= 3)          // no semicolon: does not compile
std::cout << "done\n";

— end example]

Clang puts a caret where the ; belongs and says error: expected ';' after do/while statement. MSVC reports the same mistake at the next statement (missing ';' before 'std::cout'), so on MSVC look back to the while (...) line above it.

What is the difference between while and do while?

When the condition is tested. A while loop tests it before each pass, so its body may run zero times; a do-while loop tests it after each pass, so its body runs at least once. Here both get a condition that is false from the start:

[Example 3:
int i = 10;

while (i <= 5) {          // tested first: false, body skipped
    std::cout << "while: i is " << i << '\n';
    ++i;
}

do {                      // body first, then the test
    std::cout << "do while: i is " << i << '\n';
    ++i;
} while (i <= 5);

— end example]

The while loop printed nothing. The do-while printed do while: i is 10 once, then found i <= 5 false and stopped.

Two strips of steps, left to right. While: test: false, then an arrow hopping over a grey dashed body box (0 passes) to done. Do while: body, then test: false, then done (1 pass).
Figure 2 — With a condition that is false from the start, a while loop runs its body zero times and a do-while loop once.
Behavior while do while
Tests the condition before each pass after each pass
Fewest passes 0 1
Ends with a semicolon no yes

For while on its own, see the C++ while loop.

When should you use a do while loop?

When the body has to run before the condition means anything. Counting the digits of a number is one case: every number has at least one digit, 0 included, so the first pass must happen whatever the number is.

[Example 4:
// Counts the digits of a non-negative number.
int digits_do_while(int n) {
    int digits = 0;
    do {
        ++digits;
        n /= 10;
    } while (n != 0);
    return digits;
}

— end example]

For 0, 7 and 2026 it returned 1, 1 and 4. The same body in a while (n != 0) loop returned 0 for 0, a number with one digit, because 0 never enters that loop.

Asking for input until it is valid is the other case: there is nothing to check until something has been typed. This one needs <iostream> and <limits>:

[Example 5:
int tickets = 0;
do {
    std::cout << "How many tickets (1 to 8)? ";
    if (!(std::cin >> tickets)) {
        if (std::cin.eof()) {            // the input has run out
            std::cout << "\nNo number given.\n";
            return 1;
        }
        std::cin.clear();                // working order again
        // throw away the rest of the bad line
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
                        '\n');
        tickets = 0;                     // keeps the loop going
    }
} while (tickets < 1 || tickets > 8);
std::cout << tickets << " tickets\n";

— end example]

Given the lines 0, abc, 12 and 3, it asked four times and printed 3 tickets. When a letter makes the read fail, clear() puts std::cin back in working order and ignore() throws away the rest of the line (cin in C++ explains why it needs both). If the input runs out before a valid number arrives, the eof() branch returns instead of asking forever.

How do you make a menu with a do while loop?

Show the menu, read a choice, act on it, and repeat until the choice is quit. The menu has to appear before any choice exists, which is the order a do-while runs in:

[Example 6:
int tickets = 0;
int choice = -1;
do {
    std::cout << "1 Buy a ticket\n"
                 "2 Show tickets\n"
                 "0 Quit\n"
                 "Choice: ";
    if (!(std::cin >> choice)) {
        choice = 0;                      // a failed read quits
    }
    switch (choice) {
    case 1:
        ++tickets;
        std::cout << "Bought ticket " << tickets << '\n';
        break;
    case 2:
        std::cout << "You have " << tickets << " ticket(s)\n";
        break;
    case 0:
        break;
    default:
        std::cout << "Unknown choice\n";
    }
} while (choice != 0);
std::cout << "Goodbye\n";

— end example]

Given 1, 2, 9 and 0, it showed the menu four times and answered Bought ticket 1, You have 1 ticket(s), Unknown choice and Goodbye. A failed read quits: given 1 and then the letter x, it bought one ticket and said Goodbye.

Why can’t the condition see a variable declared in the body?

Because the body is a block: a name declared inside its braces is gone by the time the condition is tested. The standard gives the body its own scope (the stretch of code where a name can be used), entered and left on every pass ([stmt.iter]).

[Example 7:
do {
    int tickets = 0;
    std::cin >> tickets;
} while (tickets < 1);    // error: tickets is gone here

— end example]

GCC says 'tickets' was not declared in this scope, and the other three reject the line too. Declare the variable before do, as tickets and choice are in the two programs above.

How do break and continue work in a do while loop?

break leaves the loop at once (the do-while loop on cppreference); inside a switch, as in the menu, it leaves only the switch. continue skips the rest of the body and goes to the condition, not back to do ([stmt.cont]):

[Example 8:
int i = 0;
do {
    ++i;
    if (i == 2) {
        continue;         // skips the print, goes to the test
    }
    if (i == 5) {
        break;            // leaves the loop at once
    }
    std::cout << i << '\n';
} while (i < 10);

do {
    std::cout << "once\n";
    continue;             // goes to the test: false ends the loop
    std::cout << "never\n";  // MSVC: C4702, unreachable code
} while (false);

— end example]

The first loop printed 1, 3 and 4: continue skipped the print at 2, and break ended the loop at 5. The second printed once and not never: continue went to the condition, false ended the loop, and the body ran once. MSVC at /W4 warns that the line after continue is unreachable.

What is do { } while (0) in a macro?

A convention for a #define macro that holds more than one statement. Wrapped in do { ... } while (0), the body runs once and the macro becomes a single statement that takes the semicolon after it, so it fits after an if without braces and before an else:

[Example 9:
#define LOG_AND_COUNT(x)                         \
    do {                                         \
        std::cout << "Sold " << (x) << '\n';     \
        sold += (x);                             \
    } while (0)
// ...
if (ok)
    LOG_AND_COUNT(3);     // one statement, so the else still fits
else
    std::cout << "Desk closed\n";

— end example]

It printed Sold 3, and sold became 3. With braces alone, the if ends at the closing brace, the ; after LOG_AND_COUNT(3) is an empty statement of its own, and the else after it no longer compiles (GCC: 'else' without a previous 'if'). In C++ an inline function is the better tool; you will meet the idiom in C headers.

While, do while or for: which loop?

Choose by what you know before the first pass:

What you know Loop
The number of passes for
The body may need zero passes while
The body must run once before the first test do while

More answers about the core language are in Language.

Questions

Does a do while loop always run at least once?

Yes. Its body runs before the condition is tested for the first time, so even a condition that is false from the start lets the body run once. A while loop with the same condition runs its body zero times.

Why does a do while loop end with a semicolon?

A do-while loop ends with its condition, and the grammar closes that with a semicolon, as it does break; and return x;. A while loop ends with its body, which already ends in ; or }. Leave the semicolon out and the program does not compile: Clang says expected ‘;’ after do/while statement.

Can you use break in a do while loop?

Yes. break ends the loop at once, and the program goes on after the while (condition);. A return in the body ends the loop too, by leaving the whole function. Inside a switch or another loop in the body, break leaves only that switch or loop.

Is a do while loop faster than a while loop?

The two differ in when the condition is tested, not in speed: a do-while loop tests it after each pass, a while loop before. Choose by the order the job needs.

How do you write an infinite do while loop?

Write do { ... } while (true); and leave it from inside the body with break, or with return to leave the whole function. The condition never becomes false, so the way out has to be a test in the body.

Can you nest do while loops?

Yes. The body of a do-while loop can be any statement, another loop included, and each loop tests its own condition.

Sources

  1. do-while loopcppreference.com
  2. [stmt.do] The do statementC++ standard working draft
  3. [stmt.iter] Iteration statementsC++ standard working draft
  4. [stmt.cont] The continue statementC++ standard working draft
  5. do-while Statement (C++)Microsoft Learn

Read next

  1. C++ while loop (and do-while): syntax and examplesLanguage · Miriam Castellanos · written for C++17
  2. C++ function pointer: syntax, callbacks and examplesLanguage · Miriam Castellanos · written for C++17
  3. Data types in C++: int, double, char, bool and moreLanguage · Miriam Castellanos · written for C++17