Monday, July 7, 2008

Scope of Variables Declared in for()

The new ANSI C++ standard specifies that variables declared as in for(int i=1; ...) have a scope local to the for statement. Unfortunately, older compilers (like Visual C++ 5.0) use the older concept that the scope is the enclosing group. Below, I list two possible problems arising from this change and their recommended solutions.

Say you want to use the variable after the for() statement. You would have to declare the variable outside of the for() statement.

Code: CPP

int i;
for(i=1; i<5; i++)
{ /* do something */ }
if (i==5) ...Say you want to have multiple for() loops with the same variables. In this case, you'd put the for statement in its own group. You could also declare the variable outside of the 'for', but that would make it slightly trickier for an optimizing compiler (and a human) to know what you intended.

Code: CPP

{
for(i=1; i<5; i++)
{ /* do something */ }
}

No comments: