tags:

views:

85

answers:

3

Why this isn't allowed:

int a = 0;
int a = 0;

but this is:

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

As far as I know code inside for loop will be executed twice whitout actually going out of its scope, so it should also be an error to define a twice.
Looking forward to your answers
Thanks.

+2  A: 

In your second case the variable a is only scoped within the for-loop. You can not access it from outside. And it will be created for every iteration of your loop again - it is like you get a new a for every iteration. It is for instance not possible to assign a value to a in one interation and to access this assigned value in any later iteration.

You should read about variable scopes to get more information about this topic. since it is really important in programming.

tanascius
+2  A: 

The code is executed twice.
But the compiler will read the definition of the 'a' variable only once.

Macmade
+8  A: 

There is a single definition within the for loop. The variable gets created, used, then destroyed at the closing curly brace and recreated in the next loop iteration. There is a single variable defined.

This is somehow similar to a variable defined in a function. The function can be called many times, but the variable is one. In fact with functions, the function can be called recursively and there will be more than one variable alive, but for each execution of the function there is a single variable defined.

EDIT: Note, as @xtofl correctly points out, that the lifetime of i is the entire for loop, while the lifetime of a is the block in the curly braces: a single iteration of the for loop.

David Rodríguez - dribeas
Mind: the difference between `i` and `a` is the scope: `i` 'lives' for the entire lifetime of the `for` construct (is invisible afterwards), while `a`'s lifetime is limited to one execution of the loop body!
xtofl
@xtofl: Good point, I have edited the question, both to add your comment and to try simplifying the similarity with function variables so that, hopefully, it will be less confusing.
David Rodríguez - dribeas