devxlogo

Scope of Variables Declared in for()

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 */ }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist