Xavier Decoret <de*****@graphics.lcs.mit.edu> wrote in message news:<bi***********@grapevine.lcs.mit.edu>...
for (int i=0;i<10;++i)
{
int i = -1;
cout<<i<<endl;
}
As far as I understand, the int declaration in the for statement makes
it declared for the scope of the for loop. So it would not be possible
to declare another int i.
On gcc-3.2.3, the above code does compile and displays 10 lines of -1.
Is it a standard compliant behaviour?
No. This is how C++ originally worked. At some point the scoping of
'for' declarations was redefined. Since this broke lots of C++ code,
many compilers implement the old behavior by default.
Consider:
#include <stdio.h>
int i;
int main(void)
{
for(int i=0; i<10; i++)
{
// int i; // legal in old C++; error under ISO C++
}
if(i==10)
printf("Old C++\n");
else
printf("ISO C++\n");
return 0;
}
When I invoke my compiler with no options, I get this:
test.cpp(11) : warning C4288: nonstandard extension used : 'i' : loop
control variable declared in the for-loop is used outside the for-loop
scope; it conflicts with the declaration in the outer scope
test.cpp(7) : definition of 'i' used
test.cpp(3) : definition of 'i' ignored
And the program prints "Old C++".
When invoked in "standard C++" mode, I get this:
test.cpp(11) : warning C4258: 'i' : definition from the for loop is
ignored; the definition from the enclosing scope is used
test.cpp(7) : definition of 'i' ignored
test.cpp(3) : definition of 'i' used
And the program prints "ISO C++".
Sam