I faced this strange behavior when I was coding. So I ask it here.
What is the scope of a for
loop when declaring variables?
This code compiles fine
for (int i = 0; i < 10; i++) { }
for (int i = 0; i < 10; i++) { }
This means both int i
are not in same scope.
But this code does not compile.
for (int i = 0; i < 10; i++) { }
int i; // Conflicts with both first loop and second one.
for (int i = 0; i < 10; i++) { }
This means the int i
in middle of loops has the same scope of first loop and the second loop.
But how can int i
in two for
loops have different scope, but the same scope with middle int i
? Because currently I see them at the same level.
I know the second code does not compile. Why does the first code compile then if there is problem in scopes. Is this an exception inside the compiler?
for(int i = ...) {} {int i; } for(int i = ...) {}
(note inner{}
) does complie.i
is before or after the firstfor
-loop. The compiler doesn't want it. Point. The compiler error prevents you from careless mistakes if you move the declaration from bottom to top. It's easy to avoid.This means the int i in middle of loops has the same scope of first loop and the second loop.
is false, and it's the main problem here.