Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
May 8, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
    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.
      for(i=1; i<5; i++)
      { /* do something */ }
Sriram Swaminathan
Thanks for your registration, follow us on our social networks to keep up-to-date