Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Keywords and Statements

The while and do-while loops

Reference for C++ while and do-while: condition-controlled loops, reading input until failure, infinite loops, and mistakes like a missing update.

while repeats its body as long as a condition is true, testing the condition before every iteration. If the condition is false at the start, the body never runs. do ... while tests after the body, so the body always runs at least once.

Choose these loops when you do not know in advance how many iterations you need: reading until the input ends, retrying until success, or consuming a queue until it is empty. For a known count, for is usually clearer.

C++
while (condition) {
    // body
}

do {
    // body
} while (condition);

Try it

C++ while, do-while and reading input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Declaring in the condition, and loop control

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
while (condition) statement
do statement while (expression);
Part Description
condition An expression or a declaration with an initializer, contextually converted to bool. For while, a variable declared here is created and tested on each iteration.
expression The do-while test, contextually converted to bool. It cannot declare a variable.
statement The loop body.

Note the semicolon after the do-while test; it is required.

Usage notes

  • Forgetting to change something the condition depends on gives an infinite loop. A loop that never ends and performs no I/O, volatile access or atomic operation is undefined behavior, because the compiler may assume loops eventually finish.
  • Test input with the read itself: while (std::cin >> x). The pattern while (!std::cin.eof()) processes the last item twice, because end of file is only detected after a read fails.
  • continue in a do-while jumps to the condition test; in a for it jumps to the step expression.
  • while (true) or for (;;) plus break is a normal way to write loops with the exit in the middle.
  • A variable declared in a while condition is destroyed and recreated each iteration, which is useful for resource handles that should not outlive an iteration.
  • do-while is mostly useful for menus and retries. The classic macro idiom do { ... } while (0) is not needed in C++ code.
  • Never modify a container's size in a way that invalidates the iterators you keep in the condition.