C++ Programming
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
for (initialization ; condition; step-expression)
statement(s);
The for construct is a general looping mechanism consisting of 4 parts:
- . the initialization, which consists of 0 or more comma-delimited variable initialization statements
- . the test-condition, which is evaluated to determine if the execution of the for loop will continue
- . the increment, which consists of 0 or more comma-delimited statements that increment variables
- . 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:
initialization
while( condition )
{
statement(s);
step-expression;
}
Example 1
// a unbounded loop structure
for (;;)
{
statement(s);
if( statement(s) )
break;
}
Example 2
// calls doSomethingWith() for 0,1,2,..9
for (int i = 0; i != 10; ++i)
{
doSomethingWith(i);
}
can be rewritten as:
// calls doSomethingWith() for 0,1,2,..9
int i = 0;
while(i != 10)
{
doSomethingWith(i);
++i;
}
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
for (variable-declaration : range-expression)
statement(s);
Example 2
std::string s = "Hello, world";
for (char c : s)
{
std::cout << c << ' ';
}
will print
H e l l o , w o r l d
.