variable scope in statement blocks

前端 未结 9 1834
梦如初夏
梦如初夏 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 22:13

    Me thinks that the compiler means to say that i has been declared at the method level & scoped to within the for loop.

    So, in case 1 - you get an error that the variable already exists, which it does

    & in case 2 - since the variable is scoped only within the for loop, it cannot be accessed outside that loop

    To avoid this, you could:

    var i = 0;
    
    for(i = 0, i < 10, i++){
    }
    
    i = 10;
    

    but I can't think of a case where you would want to do this.

    HTH

提交回复
热议问题