Declaring the Control Variable Within the for Loop

In all of the previous examples, the control variable was declared before the for loop was encountered. However, you may declare the control variable within the initialization statement of the for loop header:

<statement A>
<statement B>

for (int a = 1; a <= 5; a++)
{
  cout << setw(5)  << a;
  cout << setw(10) << a * a;
  cout << setw(10) << a * a * a;
  cout << endl;
}

<statement X>
<statement Y>

Notes on the control variable:

You should never modify the control variable within the body of the loop. The only statement that should modify it is the update expression in the for header.

The value of the control variable after the loop is the value that made the terminating condition FALSE.

Previous slide
Next slide

Back to Lesson 9 Index
Back to Outline