Reputation: 2438
For example, consider this code :
#include <iostream>
int main() {
for( int i=0; i<10; i++ );
// USING i OUTSIDE for LOOP
std::cout << i;
return 0;
}
When i compile it under g++, it says "name lookup of ‘i’ changed for ISO ‘for’ scoping, (if you use ‘-fpermissive’ G++ will accept your code)"
I think the problem is scoping. The variable i is declared in for scope and is being used outside it. Our teacher permits doing this when i asked. Is it wrong?
Upvotes: 2
Views: 5620
Reputation: 5854
The ISO 'for' scoping refers to the C++ standard. In an old standard (or, more likely, old compilers that supported it), the scope of loop variables was the scope enclosing the for statement. However, this changed, which is why you are getting that error.
A general hint about this kind of error mentioning -fpermissive: The constructs leading to these messages are usually (long) obsolete, and were allowed by either an old standard or an old compiler. Because of this, there exists old code that depends on obsolete behaviour. You shouldn't write new code that requires that option; it is more of a quick fix to get legacy code running on new GCC versions quickly.
Upvotes: 8
Reputation: 3739
Yes it is wrong. If you want to use a value outside of a loop, define it outside of the loop.
int i;
for (i=0; i<10; ++i);
std::cout << i << "\n";
Upvotes: 4
Reputation: 91
yeah it's no where possible to use the variables declare inside a for loop with all the changes in effect in the modern C++ Standards. for more detail you can always refer to cplusplus.com which is a site that contains all information based on the recent changes in the standards. A personal advice would be to you that don't just blindly go with the suggestions others make, explore on your own and then imitate the changes.
Upvotes: 0
Reputation: 1181
The variable i
is not defined outside the loop. This leads to a compile-time error.
You can do this instead:
int i = 0;
for(i; i < 10; ++i);
std::cout << i;
In that case, i
is defined outside the for-loop
, so I can "see" it
Upvotes: 1