Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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 */ }
    }
    
Sriram Swaminathan
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap