C++11C++14C++17Learn C++

General Loop Statements in Modern C++

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.

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.


Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial

Free C++Builder Community Edition

Related posts
C++C++11C++14C++17C++20Learn C++

What Is The Priority Queue (std::priority_queue) In Modern C++?

C++C++11C++14C++17C++20

What Is The Stack (std::stack) In Modern C++?

C++C++11C++14C++17C++20Learn C++

What Is The Queue (std::queue) In Modern C++?

C++C++11C++14C++17Learn C++SyntaxTemplates

What Are The Logical Operation Metafunctions In Modern C++?