Why does using the same count variable name in nested FOR loops work?

前端 未结 5 581
予麋鹿
予麋鹿 2020-12-16 16:07

Why does the following not give an error?

for (int i=0; i<10; ++i) // outer loop
{
    for (int i=0; i<10;++i) // inner loop
    {
    //...do somethin         


        
5条回答
  •  囚心锁ツ
    2020-12-16 16:33

    You are actually making a new variable with the same name as another variable. Since they are in different scopes this is allowed, and the variable in the inner scope "owns" the name. You will not be able to access the outer-scoped i inside the inner scope.

    The for loop declaration itself is part of the scope of the for loop, so counts as part of the inner-scope in the case of the second i.

提交回复
热议问题