Next: , Previous: , Up: Loop Statements   [Contents][Index]


19.6.7 for-Index Declarations

You can declare loop-index variables directly in the start portion of the for-loop, like this:

for (int i = 0; i < n; ++i)
  {
    
  }

This kind of start is limited to a single declaration; it can declare one or more variables, separated by commas, all of which are the same basetype (int, in this example):

for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  {
    
  }

The scope of these variables is the for statement as a whole. See Variable Declarations for a explanation of basetype.

Variables declared in for statements should have initializers. Omitting the initialization gives the variables unpredictable initial values, so this code is erroneous.

for (int i; i < n; ++i)
  {
    
  }