Each loop statement in C++ has its loop body which is executed repeatedly until the loop condition expression that yields a loop condition becomes false
(otherwise, the loop will run “forever”). The statement continue
can be used to interrupt the current iteration and skip the rest of the loop body to immediately check the loop condition before continuing. A whole loop statement can be completely interrupted by using one or the another termination statements: break
, goto
, return
, throw
. The break
terminates the innermost enclosing loop statement (or switch
statement, see Switch Statement in Modern C++), while the rest statements can be used to terminate the loop of any nesting level, for example:
do
and while
Loops
A do
-loop executes its body at least once because the expression that yields a loop condition is evaluated and checked after the each iteration, for example:
A while
-loop is similar to do
-loop except that the loop condition is evaluated and checked before the each iteration, for example:
Please note, either do
-loop or while
-loop are preferable when the loop variable (or something that affects the loop condition) must be updated in the loop body. (Usually, the number of iterations is unknown beforehand in this case.)
for
Loop
The general for
-loop statement should be used instead of range-for-statement when a greater control over the loop is required. The syntax is follow:
Any of the expressions above can be omitted, so the simplest form of the general for
-loop is for(;;);
(which just blocks the execution thread forever). The init-expression has to be used to declare variables into the scope of for
-loop statement, the loop-condition-expression is evaluated before the each iteration, and the update-expression is evaluated after the each iteration and has to be used to update the loop variable(-s) (which are usually declared in the init-statement, but not necessarily), for example:
Please note, that for
-loop is preferable when there is an obvious loop variable, or where a loop variable is naturally updated after the each iteration.