What is the scope of a while
and for
loop?
For example, if I declared an object within the loop, what is its behavior and why?
int d;
// can use d before the loop
for(int a = 0; a < 5; ++a) // can use a or d in the ()
{
int b;
// can use d, a, b in the {}
}
int c;
// can use d, c after the loop
a
and b
are only visible in the scope of the for loop. The scope includes what's in the loops ()
and {}
In the following examples all the variables are destroyed and recreated for each iteration of the loop except i
, which persists between loop iterations and is available to the conditional and final expressions in the for loop. None of the variables are available outside the loops. Destruction of the variables inside the for loop body occurs before i
is incremented.
while(int a = foo()) {
int b = a+1;
}
for(int i=0;
i<10; // conditional expression has access to i
++i) // final expression has access to i
{
int j = 2*i;
}
As for why; loops actually take a single statement for their body, it just happens that there's a statement called a compound statement created by curly braces. The scope of variables created in any compound statement is limited to the compound statement itself. So this really isn't a special rule for loops.
Loops and selection statements do have their own rules for the variables created as a part of the loop or selection statement itself. These are just designed according to whatever the designer felt was most useful.
Just wanted to add that variables declared in the for or while loop are also scoped within the loop. For example:
for (int index = 0; index < SOME_MAX; ++index)
{
...
}
// index is out of scope here.
int a;
for(int b=0; b<10; ++b) {
int c;
}
scopes as if it were:
int a;
{
int b=0;
begin:
if (b<= 10)
{
{
int c;
}
++b;
goto begin;
}
}
The purpose is so that variables go out of scope at clearly defined sequence points.