From Appmethod Topics
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index




for ( [<initialization>] ; [<condition>] ; [<increment>] )  <statement>


The for statement implements an iterative loop.

<condition> is checked before the first entry into the block.

<statement> is executed repeatedly UNTIL the value of <condition> is false.

  • Before the first iteration of the loop, <initialization> initializes variables for the loop.
  • After each iteration of the loop, <increments> increments a loop counter. Consequently, j++ is functionally the same as ++j.

In C++, <initialization> can be an expression or a declaration.

The scope of any identifier declared within the for loop extends to the end of the control statement only.

A variable defined in the for-initialization expression is in scope only within the for-block. See the description of the -Vd option.

All the expressions are optional. If <condition> is left out, it is assumed to be always true.


This example illustrates the use of the keyword for.

// An example of the scope of variables in for-expressions.

// The example compiles if you use the -Vd option.
#include <iostream>
using std::cout;

int main() 
  for (int i = 0; i < 10; i++)
     if (i == 8)
     cout << "\ni = " << i;
  return i;  // Undefined symbol ‘i’ in function main().