scope of a variable declared in a for loop
Hello all code gurus,
Here is another issue which has bothered me for years.
One poor soul dared to ask a while ago and the thread turned ugly --- with authors radically defending one development environment over the other and such things.
So please here just try to stick to the C++ language specification.
What is the scope of a loop variable?
I was of the opinion that the scope of i (see code snippet below) must be limited to lines within the loop.
Some compilers exhibit different behavior regarding this syntax.
Can anyone verify the proper language specification here?
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
for(register int i = 0; i < 10; i++)
{
cout << i << endl;
}
#ifdef __GNUC__
#else
// This line should not compile in my opinion.
cout << i << endl;
#endif
return 1;
}
Thanks. Don't get too rowdy...
Chris.
:confused:
Just for fun (Anthony, please take note :) )
The old book I have (TC++PL, 2nd edition) says like this:
Code:
iteration-statement:
...
for ( for-init-statement; condition(opt); expression(opt) ) statement
condition:
expression
type-specifier declarator = expression
That means one can write:
Code:
int condition( int ai )
{
// do something creative
return ai;
}
for ( int i = 0; int j = condition(i); i++ )
{
// use i and j
}
VC++ does not compile the code above (missing int before; ). It’ll be interesting to find out what the others compilers say about this piece of code.
Is this of any practical use? Maybe…
One can say it looks ugly... Maybe...