What does the C++ standard say?
What does the C++ standard say with regards to the following piece of code. I am attempting to compile someone else's code on two different compilers, and on one it fails. The code is something like this:
Code:
const int iMax = 50;
void SomeFunction()
{
for(int i=0; i<iMax; ++i)
doSomething(i);
for(int i=0; i<iMax; ++i)
doSomethingElse(i);
}
The reason one fails is it says that i is defined twice (in both for statements). So the question I have is does defining a variable within a for loop limit the scope of the variable to the for loop? Or does it effectively define the variable in the scope before the loop? Which compiler is more compliant to the standard in this particular area?
Thanks,
Kevin
Re: What does the C++ standard say?
I know this isn't the VC++ forum, but...
MSVC++ doesn't adhere to the standard, but the 7.x versions of the MS compiler offer a switch that you can use to force compliance in this respect. From MSDN:
Quote:
The C++ standard says that a variable declared in a for loop shall go out of scope after the for loop ends. For example:
Code:
for (int i = 0 ; i < 5 ; i++) {
// do something
}
// i is now out of scope under /Za or /Zc:forScope
By default, under /Ze, a variable declared in a for loop remains in scope until the for loop's enclosing scope ends.
/Zc:forScope enables standard behavior of variables declared in for loops without needing to specify /Za.
It is also possible to use the scoping differences of the for loop to redeclare variables under /Ze as follows:
Code:
// for_statement5.cpp
int main()
{
int i = 0; // hidden by var with same name declared in for loop
for ( int i = 0 ; i < 3; i++ )
{
}
for ( int i = 0 ; i < 3; i++ )
{
}
}
This more closely mimics the standard behavior of a variable declared in a for loop, which requires variables declared in a for loop to go out of scope after the loop is done. When a variable is declared in a for loop, the compiler internally promotes it to a local variable in the for loop's enclosing scope even if there is already a local variable with the same name.