2

I'm trying to use a program written a few years ago and compiled in a previous version of MS VC++ (I am using VC++ 2008). There are a lot (hundreds) of instances similar to the following:

int main () {
  int number = 0;
  int number2 = 0;

  for (int i = 0; i<10; i++) {
   //something using i
  }

  for (i=0; i<10; i++) {
   //something using i
  }

  return 0;
}

I'm not sure which version it was originally compiled in, but it worked. My question is: how did it work? My understanding is that the i variable should only be defined for use in the first loop. When I try to compile it now I get the error "'i': undeclared identifier" for the line starting the second loop, which makes sense. Was this just overlooked in previous versions of VC++? Thanks!

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Jade
  • 57
  • 8

1 Answers1

5

An earlier version of MSVC had this "misfeature" in that it leaked those variables into the enclosing scope.

In other words, it treated:

for (int i = 0; i<10; i++) {
    // something using i
}

the same as:

int i;
for (i = 0; i<10; i++) {
    // something using i
}

See the answers to this question I asked about a strange macro definition, for more detail.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Ok thanks. That makes sense. Not really looking forward to changing all those errors... – Jade Oct 14 '10 at 17:00
  • Maybe a global search and replace for `for (i =` with `for (int i =` ? Though that may give you errors going the _other_ way. – paxdiablo Oct 14 '10 at 17:03
  • Your previously asked question was very insightful, thanks for the link! Maybe you're right, doing that search and replace will probably be less work, even if I have to go back and fix some other resultant errors. – Jade Oct 14 '10 at 17:20