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

5

16

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?

Ferri answered 6/3, 2010 at 17:44 Comment(2)
As you probably already now, while it works, you shouldn't do it. It can result in less readability and some very nasty bugs.Otherworldly
In Java or C this definitely gives an error. Java doesn't allow duplicate local variables whatever the scope might me. In the case of C++, Duplicate variables can be initialized in different scopes (here scope means { ... }). The priority of the variable value in runtime respects scope. If there is no duplicate variable initialized in the inner scope, then the variable of the outer scope can be accessed in the inner scope.Struck
M
19

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.

Mcferren answered 6/3, 2010 at 17:46 Comment(4)
@Justin is there no way to access the outer loop's i whatsoever ?Salomon
No. Just name the inner loop's i something else. It's common to see nested loop index variables as progressive characters from the alphabet starting with i, j, k, etc.Jolt
Doesn't the inner for loop override the outer loop, since i is redefined in the outter for looper?Labour
@rahultyagi If you want to access the outer loop's "i", why would you re-initialize a duplicate variable in the inner for loop. If you want to access the outer loop variable you should initialize variables(in this case indices) with different names.Struck
F
3

The C++ compiler accepts this as valid, as the scope of the second is only within the { } braces. If you implement the same in C, you will see an error like this:

$ gcc test.c
test.c: In function ‘main’:
test.c:10: error: ‘for’ loop initial declaration used outside C99 mode
test.c:12: error: ‘for’ loop initial declaration used outside C99 mode

This is illegal in most C dialects; it is a legal C++ declaration, and so may be accepted if you are compiling C with a C++ compiler:

for( int i=0; i<5; ++i){}

It is common to have a loop iterator only in the scope of the loop in C++, but C makes sure (specially with the C90, not C99), that the declaration is outside the scope of the loop. Hope that helps ... :-)

So, when you declare another FOR loop within the older one, then the scope start fresh and your code compiles without any error in C++ or C99. This is the usual accepted norm for a scope declaration.

Frederic answered 7/3, 2010 at 1:53 Comment(2)
It is the same concept even when using the same variable in the same scope - Eg: for(int i=0;i<10;i++){//some code} for(int i=0;i<10;i++){//some other code} Is valid in C++ but invalid in most C dialects.Caramelize
If you try this in Python, it'll also produce incorrect results. It see both the "inner i" and the "outer i" as the same. As a result, the OP's code will see 10 iterations, and NOT 100 iterations (10x10)Adrianeadrianna
B
2

The best way to understand this is to think about everything between the ( and ) when you declare a for loop as being inside the braces of that for loop, at least as it relates to the scope.

To understand this, consider a function in which you have no x variable declared, then the following code inside will give you an error. (We are also assuming that you have no other x variable defined globally.)

for (int x = 0; x < 10; x++)
{
    something();
}
x++; // error, x is not defined.
Bunkhouse answered 6/3, 2010 at 17:51 Comment(0)
C
1

The inner loop starts another level of scoping, for loops start the scope in the loop definition so the second i is in a new scope.

see

http://en.wikibooks.org/wiki/C%2B%2B_Programming/Scope#Scope_using_other_control_structures

Cherub answered 6/3, 2010 at 17:50 Comment(0)
I
-2

ARE YOU SURE YOU DON'T GET AN ERROR WHILE EXECUTING THIS ....?

you are trying to define the two int variable within the same boundary .due to this this will generate the error . in c# if u try out the same code you will get the error

Error 1 A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'parent or current' scope to denote something else

Inbreed answered 7/3, 2010 at 9:36 Comment(1)
YES I AM SURE.... ! No that I understand the issue better, I think the C++ behaviour is correct.Ferri

© 2022 - 2024 — McMap. All rights reserved.