tags:

views:

130

answers:

5

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?

+12  A: 

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.

fbrereto
Handy link with C++ examples of different scopes: http://h30097.www3.hp.com/docs//base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_016.HTM
Justin Johnson
+1  A: 

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

shipmaster
+2  A: 

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.
Aaron
A: 

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.

gagneet
A: 
sandy101
YES I AM SURE.... ! No that I understand the issue better, I think the C++ behaviour is correct.
M Perry