Variables can be redeclared in inner scopes. This is called shadowing. However, what you're trying to do is redeclare the variable in the same scope.
for (...) {
int a = 0;
}
This creates a variable a
several times. At the end of each iteration, the variable is deallocated and a new one is created.
int a = 0;
for (...) {
int a = 1;
}
This is similar. The second a
is a new variable that only exists inside of the loop. Once the loop is over, the original a
is back and still has value 0
.
int a = 0;
int a = 1;
Here, we are trying to create two variables in the same scope with the same name. The C++ standard explicitly disallows this. There's no mechanical reason that this must be disallowed, but since there are almost no reasons you would want to intentionally do this, the standard forbids it, as it is much more likely that you intended to make an assignment. If you really want two variables with the same name, you can use an explicit block.
int a = 0;
{
int a = 1;
}
But there's really no reason to do this.