C Reference ยท Keywords and Statements
The while and do-while statements
Reference for the C while and do-while loops: how the condition is tested, when the body runs at least once, sentinel loops and common mistakes.
while repeats a statement as long as its condition is true, testing before each iteration, so the body may never run. do ... while tests after each iteration, so the body always runs at least once.
Use them when you do not know in advance how many iterations you need: reading until the input ends, searching until something is found, or retrying until an operation succeeds.
while (condition) statement 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 scanf or fgets), 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 scanf or fgets), it gets the next line from this box.
Syntax
while ( expression ) statement do statement while ( expression ) ;
| Part | Description |
|---|---|
expression |
Scalar controlling expression, compared against zero. |
statement |
The loop body. Use braces. |
Notes on the grammar: the do-while form ends with a semicolon; while does not. while (1) or while (true) makes an infinite loop.
Undefined behavior: none from the keyword itself. In C11 and later, a loop whose controlling expression is not a constant expression and that has no side effects, I/O or atomic operations may be assumed by the compiler to terminate.
Usage notes
- Pre-test vs. post-test. Choose
do-whileonly when the first pass must happen, such as a menu or "ask again until valid" input. - Stray semicolon:
while (i < 3);is an empty loop and hangs if nothing in the condition changes. - Update the variable. A forgotten
i++creates an infinite loop; the compiler cannot warn about all of them. - Reading input: test the return value, not
feof().while (scanf("%d", &x) == 1)stops correctly;while (!feof(f))runs once too often. See feof and ferror. - Multi-statement macros are wrapped in
do { ... } while (0)so that they behave like one statement, even before anelse. See macro pitfalls. breakandcontinuework in both forms; indo-while,continuejumps to the condition test. See break and continue.- When a counter is natural,
forkeeps the three parts together.
Related
for,breakandcontinue,goto,ifandelse- Lessons: while and do-while loops, User input