c++/2288: Variable declared in for-loop-header is in wrong scope

Wolfgang Bangerth bangerth@ticam.utexas.edu
Thu Nov 14 16:09:00 GMT 2002


Still happens with recent CVS. A smaller, self-contained testcase is this:
------------------------
void f(int);
int main() {
   for (int i=0;;++i) {
     int i=5;
     f(i);
   }
   return 0;
}
-----------------------
I don't get an error upon the second declaration of "i", although it 
should be in the same scope as that declared in the loop-header. If I use 
-Wshadow, it says
x.cc: In function `int main()':
x.cc:4: warning: declaration of `i' shadows a previous local
x.cc:3: warning: shadowed declaration is here

So one can assume that gcc generates two nested scopes for this construct, 
in the outer one those variables are placed which are declared in the loop 
header, in the inner one those go that are declared in the loop body. I 
think this is not the intent of the standard...

The C frontend in gnu99 mode suffers from the same problem, by the way.

Regards
  Wolfgang

-------------------------------------------------------------------------
Wolfgang Bangerth              email:           bangerth@ticam.utexas.edu
                               www: http://www.ticam.utexas.edu/~bangerth




More information about the Gcc-bugs mailing list