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.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.
The code is executed twice.
But the compiler will read the definition of the 'a' variable only once.
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.
精彩评论