-
Syntax
-
Here's how a do-while loop looks
do
do-while body
while ( cond )
This looks very much like an if statement. cond
is a condition. The while body must either be
a block or a single statement.
A single statement is now extended to mean:
- an assignment statement
- a declaration
- an empty statement
- an if-else or if statement
- a switch statement
- a while statement
- a do-while statement
-
Semantics
-
Again, to remind ourselves of the do-while loop.
do
do-while body
while ( cond )
The semantics of how to run this loop are:
- Run the do-while
- Evaluate cond
- If cond evaluates to true, go back to step 1
- If cond evaluates to false, skip to
next statement
-
At Least One Iteration
-
The main difference between while and do while
is that do while always runs at least one iteration.
Even though there is this difference, I find I rarely use
do while. You can just use while. However,
the choice is up to you.