Reputation: 34523
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?
Upvotes: 48
Views: 56304
Reputation: 53037
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 {}
Upvotes: 17
Reputation: 88155
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.
Upvotes: 48
Reputation: 81
I thought it would be worth mentioning:
Some compilers may have an option which effects the scope of variables created within the for loop initializer. For example, Microsoft Visual Studio has an option /Zc:forScope (Force Conformance in for Loop Scope). It defaults to standard c++ behavior. However, this can be changed so that the for loop variable is kept alive outside the for loop scope. If you are using VS it might be useful to be aware that this option exists so you can make sure its set to the desired behavior. Not sure if there are any other compilers which have this option.
Some compilers may eliminate code it thinks is unnecessary, due to optimization settings and "Dead Store" elimination. For example, if the variable being changed inside the loop isn't read anywhere outside the loop, the loop itself may be discarded by the compiler.
For example, consider the following loop:
int cnt = 0;
int trys = MAX_INT;
while (trys-- > 0)
{
cnt += trys;
}
it is possible that some compilers may discard [the contents of] the loop, because the variable Cnt isn't being used after the loop.
Upvotes: 8
Reputation: 2160
Check out this code
#include < stdio.h >
int i = 10;
int main() {
for(int i=0; i<3; i++) {
fprintf(stdout," for i = %d & upper i = %d\n",i,::i);
}
while (i>3) {
int i = 30;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
i++;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
}
fprintf(stdout,"i = %d \n",i);
}
In the code above, the global variable i is different from one which is controlling the for loop.
It will print
for i = 0 & upper i = 10
for i = 1 & upper i = 10
for i = 2 & upper i = 10
when while loop is executed - the variable i defined inside while is having local scope, where as the variable under (i > 3) follows the global variable, and doesn't refer to local scope.
Dipan.
Upvotes: 3
Reputation: 66922
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.
Upvotes: 5
Reputation: 5963
The variable is within the scope of the loop. I.e. you need to be within the loop to access it. It's the same as if you declared a variable within a function, only things in the function have access to it.
Upvotes: 2
Reputation: 101456
for( int i = 0; i < 10; ++i )
{
string f = "foo";
cout << f << "\n";
}
// i and f are both "gone" now
In the above sample code, both i
and f
are scoped within the {
{ and }
} When the closing brace is executed, both variables fall out of scope.
The reason for this is simply that the Standard says so; that's how the C++ language works.
As for motivation, consider that this can be used to your advantage:
for( ...)
{
std::auto_ptr<SomeExpensiveObject> obj(new SomeExpensiveObject);
}
In the above code, we are using an RAII smart pointer to "own" the expensive object we created within the loop. The scoping semantics of the for
loop dictate that after each execution of the loop, the object that was created during that iteration will be destroyed.
Upvotes: 4
Reputation: 1955
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.
Upvotes: 7
Reputation: 3100
In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.
while (some_condition == true)
{
int myVar = 3;
}
cout << myVar << endl; // This will cause a compilation error
Upvotes: 3
Reputation: 91598
Anything declared in the loop is scoped to that loop and cannot be accessed outside the curly braces. In fact, you don't even need a loop to create a new scope. You can do something like:
{
int x = 1;
}
//x cannot be accessed here.
Upvotes: 35