Scope of for-loop variables

I am porting some VC++ 6 code to VC++ 2005 and one major pain in the neck is the for-loop variable scope. The /Zc:forScope compiler option is on by default in VC++ 2005 and I believe it was off by default in VC++ 2003 (though people were advised to turn it on). So, code such as this won’t compile :-

for(int n=0; n<a.GetSize(); n++)


for(n=0; n<x; n++) // <- error C2065: 'n' : undeclared identifier

There’s lots and lots of similar code occurrences in the VC++ 6 code I am working on and I think the next few days are going to be fun for me! BTW, before anyone thinks I am mad at the VC++ team, this scoping rule is standard C++ behavior, so it’s not their fault at all. And that’s exactly why I am going to fix the code rather than disable the compiler option (which I can but won’t).


6 thoughts on “Scope of for-loop variables

  1. No Nish it was not on by default in VS 2003. I can asure you.
    I am right now porting a large VC++6 code base to VC++ 2003 and flipped the switch for
    loop standard conformance on purpose.

    I also faced a lot of loop code in need for reorganization.

    Even some nasty practices like using the loop variable ouside the scope of the loop.

    This just shows, that a non standard compiler causes people to write sloppy code.

  2. Martin

    I saw lots of code where the loop variable was used outside the loop too. It’s the compiler’s fault than the programmer’s fault as you can’t expect a programmer to sit and verify his code with the standard every single time. It’s the compiler that should catch errors like that.

  3. Dunno Paul, it wasn’t that way in the standard long ago – I think it was a relatively recent change to the standard. Like you said, it’s more consistent than the previous rule – so makes better sense I guess.

  4. You’ve always been able to do this:
    if ( char c = GetAChar() ) { … }
    and the variable was scoped to the if block. IIRC the fact that the scoping rule for
    variables in for loops was different was just a mistake.

  5. sigh…. This is also an error on eVC4.0
    for(int n=0; n<a.GetSize(); n++)


    for(int n=0; n<a.GetSize(); n++)


    Compiler show me some messages lisk “redefinition blar blar”

    Pliz Pliz Don’t change sth like that…!! HaHa!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s