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++20Introduction to C++Learn C++

Learn Copy Constructors in C++ Classes

C++C++11C++14C++17Introduction to C++Learn C++Syntax

Learn How To Use Types Of Destructors In C++?

C++C++11C++14Learn C++Syntax

How To Convert u32string To A wstring In C++

C++C++11C++14C++17C++20Introduction to C++Learn C++

How To Learn The Move Constructors In Modern C++?