Search code examples
c++visual-c++undeclared-identifier

Are undeclared variables legal in C++?


I'm totally baffled by some code I'm trying to compile. The compiler gives me several dozen "undeclared identifier" errors. They all seem to be local loop variables like this:

for ( i = 0; i < 100; i++ )

I could easily fix it, but I don't understand how that code could have compiled for other people. And those files haven't been touched in ages.

Is there some kind of compiler flag for VC++ that automatically assumes int for undeclared variables? I couldn't find it. What gives?


A minimal full code example that replicates the problem:

for ( int i = 0; i < 100; i++ );
for ( i = 0; i < 100; i++ );

Solution

  • The question is related to the scope of variables declared in a for statement. The standard defines this scope to be restricted to the for loop itself. But some compilers support non-standard legacy extensions that used to extend this scope to the enclosing bloc.

    To compile such code with MSVC, add compiler switch /Ze

    See MSDN docs for details.

    A comment below suggests /Zc:forScope, but according to this MSDN page that's not right.

    By the way, G++ has a similar -fno-for-scope switch.