Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

scoping

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 something
    }
//...do something else
}

The way I understand it, variables in braces ({...}) are in scope only within these braces. But the inner loop is inside the braces of the outer loop. So as soon as I declare int i=0 for the inner loop, shouldn't I get an error about multiple definitions?

like image 984
M Perry Avatar asked Mar 06 '10 17:03

M Perry


People also ask

Can nested for loops use the same variable?

In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. Consequently, nested loops in which the target variables have the same name in fact share a single variable.

Why is it a bad idea to reuse the same identifier in different nested scopes?

You may get compiler warnings if you create a variable with the same name as another variable in an outer scope. With good reason, because that is going to be confusing and error prone. Avoid it whether you get warnings or not.

Can you use the same control variable for the inner loop as you do for an outer loop?

It will be a different object. They will not affect each other.

How many nested for loops is too many?

Microsoft BASIC had a nesting limit of 8. @Davislor: The error message refers to the stack size in the compiler, which is also a program, and which is recursively processing the nested-looped construct.


1 Answers

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.

like image 170
fbrereto Avatar answered Sep 21 '22 19:09

fbrereto