Thursday, October 12, 2006

Scope Error ?

Why does this code give a compile time error ??

void test
for(int i=0;i<10;i++)
int i=2;

i too was pondering over the same until i stumbled upon a entry in MSDN blogs. Accordingly, the scope of a local variable declared in a local-variable-declaration is the block in the which the declaration occurs.

There is two scopes of i.
1. The child scope inside the loop
2. The function scope.

According to the defination given in language spec in section 3.7, the scope of "i" would be the entire test function.

This would mean that the "i" outside the loop would have its scope in the entire function despite being declared at a latter stage.
This is the reason the compiler shows the error.