audiFanatic
audiFanatic

Reputation: 2514

Visual C++ 6 Variable Scope Bug

So I've inherited some code that's about as old as me and I'm tasked with maintaining it. The code was written using Visual C++ 6, so it's not modern by any stretch of the imagination.

Anyway, I decided to try and upgrade the solution (or I guess workspace as Microsoft called it back then) so that I can use it with Visual Studio 2013 and use a somewhat modern IDE (I think I'd rather use Emacs or plain-old notepad over VC++ 6). After having changed the character set for the MFC library, I'm getting a whole bunch of undeclared identifier errors (on the order of about 1100 errors). A LOT of them seem to stem from a temporary variable scoping issue, that has me wondering how on earth this code was allowed to compile previously. I'm seeing a lot of stuff like this:

void MyClass::MyFunc() 
{
    for(int i=0;i<56;i++)
    {
      // do some stuff
    } 

    // command hardware
    for(i=0;i<m_pinfo->vc_num;i++)
    {
      // do some more stuff
    }
}

Miraculously, this code compiles just fine in VC++ 6, but (thankfully) not in VS 2013. Notice how the variable i was declared within the scope of the first for loop, but it was then used again in the second for loop. This kind of code is littered throughout the program.

Using VC++ 6's Goto Definition tool, it's telling me that there's an ambiguity between the variable i (but it still compiles!) and several seemingly unrelated variables and parameters called 'i' that are in separate .cpp files all-together, some of them defined in structures even.

What could be going on here? For all intents and purposes, I cannot see how this code is allowed to compile in VC++6.

Upvotes: 2

Views: 650

Answers (2)

NathanOliver
NathanOliver

Reputation: 180935

It is a extension in MSVC++ 6. Variables declared in a for loop are not accessible outside of the for loop scope per the standard. If you need to get this non standard behavior in newer version on MSVS then you can Enable the /Zc:forScope flag

I would suggest that you fix the for loops so you have standard conforming code. This way people who do not know this extension exists will not be surprised by the code.

Upvotes: 2

YSC
YSC

Reputation: 40100

In old C, you could define an int without having to specify its type. I suspect VC++6 to obey this ancient rule and implicitly defining a new i variable for the second loop.

If I'm right, this should also compile:

void MyClass::MyFunc() 
{
    for(i=0;i<56;i++)
    {
      // do some stuff
    } 

    // command hardware
    for(i=0;i<m_pinfo->vc_num;i++)
    {
      // do some more stuff
    }
}

And this should print 1 2 3 4

void MyClass::MyFunc() 
{
    for(i=1;i<3;i++)
    {
      std::cout << i << ' ';
    } 

    // command hardware
    for(;i<5;i++)
    {
      std::cout << i << ' ';
    }
}

Upvotes: 0

Related Questions