11B. Additional Features of For-Loops

Declaring a variable in a for-loop heading

The first part of a for-loop heading can create a new variable. But a variable created there can only be used in the for-loop heading and body. For example
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
creates variable i that can only be used in this for-loop. You are not allowed to say
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
  printf("%d\n", i);
since that tries to use i outside of the for-loop.

Typically, a variable that is controlled in a for-loop heading is only intended to be used within the loop, and it is a good idea to limit its scope. If you need to use the loop control variable after the loop, declare it before the loop.


Omitting part of a for-loop heading

Every for-loop heading has exactly two semicolons. But you can omit any (or all) of the three parts that are separated by semicolons.
  • If the first part is empty, no initialization is done.

  • If the second part is empty, it is assumed to be true, so the loop keeps going until stopped some other way.

  • If the third part is empty, no update is added to the end of the body.

For example,
  for(; k < n; k++)
  {
    ...
  }
assumes that k has already been initialized.

But do not omit any of the three parts without a good reason. Each of the three parts of a for-loop heading has a purpose. Instead of

  int k = 0;
  for(; k < n; k++)
  {
    ...
  }
write
  int k;
  for(k = 0; k < n; k++)
  {
    ...
  }
The standards for this course require you not to omit any part of a for-loop heading without good reason.