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.
while (condition) { // body } do { // body } while (condition);
Try it
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.
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
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 patternwhile (!std::cin.eof())processes the last item twice, because end of file is only detected after a read fails. continuein ado-whilejumps to the condition test; in aforit jumps to the step expression.while (true)orfor (;;)plusbreakis a normal way to write loops with the exit in the middle.- A variable declared in a
whilecondition is destroyed and recreated each iteration, which is useful for resource handles that should not outlive an iteration. do-whileis mostly useful for menus and retries. The classic macro idiomdo { ... } 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.
Related
- for
- Range-based for
- break and continue
- Tutorial: while loops, User input