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)?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityYes, 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 afor
loop's initializer go out of scope after the for loop. Under/Zc:forScope-
and/Ze
, thefor
loop's initializer remains in scope until the local scope ends.
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;
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.
less than
not less than or equal to
Jul 14, 2016 at 16:34
int x = expression;
if need be do it before the for loop.