Are undeclared variables legal in C++?

453 views Asked by At

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++ );
2

There are 2 answers

3
egrunin On BEST ANSWER

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.

0
Amxx On

C++ is a typed langage. One of the concequences is that you HAVE to declare variables before using them.

This seems strange to many but it contributes to have good coding practices, as weel as giving you errors when you do typos in your variables names.

On of the easy to understand concequences is that it helps you calling the good version of an overloaded function by checking the type of the arguments. This Check can be done at compile time which increase performance at runtime.

This is inherited from C which is choser to assembly then C++. Allocating variables means allocating the memory space on the stack.

You can always try and have a look at the auto keyword in c++11 and c++14, but before that make sure you know what a type is (like was is the difference between 1, 1.0 and 1.f)