Last modified on 16 April 2013, at 01:49

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:

  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.

Note:
Variables declared and initialized in the loop initialization (or body) are only valid in the scope of the loop itself.

The for loop is equivalent to next while loop:

 initialization
 while( condition )
 {
   statement(s);
   step-expression;
 }


Note:

Each step of the loop (initialization, condition, and step-expression) can have more than one command, separated by a , (comma operator). initialization,condition, and step expression are all optional arguments. In C++ the comma is very rarely used as an operator. It is mostly used as a separator (ie. int x, y; ).

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

.