variable scope in statement blocks

前端 未结 9 1847
梦如初夏
梦如初夏 2020-12-01 21:14
for (int i = 0; i < 10; i++)
{
    Foo();
}
int i = 10; // error, \'i\' already exists

----------------------------------------    

for (int i = 0; i < 10; i         


        
9条回答
  •  时光说笑
    2020-12-01 21:57

    From the C# spec on local variable declarations:

    The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs.

    Now, of course, you can't use i before it is declared, but the i declaration's scope is the entire block that contains it:

    {
        // scope starts here
        for (int i = 0; i < 10; i++)
        {
            Foo();
        }
        int i = 10;
    }
    

    The for i variable is in a child scope, hence the collision of variable names.

    If we rearrange the position of the declaration, the collision becomes clearer:

    {
        int i = 10;
    
        // collision with i
        for (int i = 0; i < 10; i++)
        {
            Foo();
        }
    }
    

提交回复
热议问题