|
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.
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.
|
|