variable scope in statement blocks

前端 未结 9 1828
梦如初夏
梦如初夏 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条回答
  •  -上瘾入骨i
    2020-12-01 22:07

    In the first example, the declaration of i outside of the loop makes i a local variable of the function. As a result, it is an error to have another variable name i declared within any block of that function.

    The second, i is in scope only during the loop. Outside of the loop, i can no longer be accessed.

    So you have seen the errors, but there is nothing wrong with doing this

    for (int i = 0; i < 10; i++)
    {
      // do something
    }
    
    foreach (Foo foo in foos)
    {
       int i = 42;
       // do something 
    }
    

    Because the scope of i is limited within each block.

提交回复
热议问题