C++ Programming/Programming Languages/C++/Code/Keywords/for

The for keyword is used as special case of a pre-conditional loop that supports constructors for repeating a loop only a certain number of times in the form of a step-expression that can be tested and used to set a step size (the rate of change) by incrementing or decrementing it in each loop.


 * Syntax

The for construct is a general looping mechanism consisting of 4 parts:
 * 1) . the initialization, which consists of 0 or more comma-delimited variable initialization statements
 * 2) . the test-condition, which is evaluated to determine if the execution of the for loop will continue
 * 3) . the increment, which consists of 0 or more comma-delimited statements that increment variables
 * 4) . and the statement-list, which consists of 0 or more statements that will be executed each time the loop is executed.

The for loop is equivalent to next while loop:

Example 1

Example 2

can be rewritten as:

The for loop is a very general construct, which can run unbounded loops (Example 1) and does not need to follow the rigid iteration model enforced by similarly named constructs in a number of more formal languages. C++ (just as modern C) allows variables (Example 2) to be declared in the initialization part of the for loop, and it is often considered good form to use that ability to declare objects only when they can be initialized, and to do so in the smallest scope possible. Essentially, the for and while loops are equivalent. Most for statements can also be rewritten as while statements.

In C++11, an additional form of the for loop was added. This loops over every element in a range (usually a string or container).


 * Syntax

Example 2

will print H e l l o,  w o r l d.