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.

  1. Say you want to use the variable after the for() statement. You would have to declare the variable outside of the for() statement.
  2.  int i;for(i=1; i<5; i++){ /* do something */ }if (i==5) ...
  3. 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.
  4.  {  for(i=1; i<5; i++)  { /* do something */ }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: