1

I'm using some code, which uses variables declared in a loop after the loop. For example


for (int i = 0; i != 10; i++)
{
   // do stuff
}

int x = i;

I get the "i" undefined error. Is there a compiler switch to change this (in VC++ 2015)?

2
  • This is wrong. I assume that 10 is just an example, but it could be a more complex expression, so just do int x = expression; if need be do it before the for loop.
    – Bent
    Jul 14, 2016 at 16:09
  • 1
    Incidentally, the other guy is right. Using != for the loop test is begging for trouble. (A certain former Grand Admiral of Starfleet Command is still smarting from the day a young ensign pointed that one out to him, and it turned out to be exactly the bug we were chasing on an otherwise very nice piece of code.) Jul 14, 2016 at 18:48

3 Answers 3

4

Yes, apparently there is such an option. I strongly suggest you avoid using it. Fix the code instead.

In early versions of C++, the scope of a variable defined in a for loop header extended to the end of the block containing the loop, making the code in your question valid. In modern versions of the language, the scope ends at the end of the loop, making your code invalid. The change was made in the 1998 ISO C++ standard, if not earlier, so it seems you're looking at some rather old code.

According to this web page for Visual Studio 2015, the /Zc:forScope- option tells the compiler to implement the old semantics.

The /Zc:forScope- option is deprecated and will be removed in a future release. Use of /Zc:forScope- generates deprecation warning D9035. Standard behavior is to let a for loop's initializer go out of scope after the for loop. Under /Zc:forScope- and /Ze, the for loop's initializer remains in scope until the local scope ends.

3

try this...

int i = 0;    
// don't use != You could end up with an infinite loop if something ever steps over i=10
for (; i < 10; i++)
{
   // do stuff
}

int x = i;
2

Do it right or don't do it at all.

unsigned i; /* NOT int: i is constrained to 0..11 by the for-stmt */

for (i = 0; i < 10; i++)
{
   // do stuff
}

int x = i;

If you want i to be in scope outside the for-loop, declare it outside the for-loop. The whole point of allowing the declaration in the for-statement is to limit the scope of the index to the loop, and not allow it to sneak out.

3
  • The code was already written like this. Some c++ compilers seem to accept it
    – Dennis R
    Jul 14, 2016 at 16:18
  • based on the example it should be less than not less than or equal to Jul 14, 2016 at 16:34
  • @MatthewWhited: You're right! Thanks for catching that! I've corrected it. Jul 14, 2016 at 18:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.