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