I noticed that the scope rules of the for loop are different for C and C++.
For example, the code below is legal in the C compiler, but not legal in the C++ compiler.
for (int i = 0; i < 10; ++i) {
int i = 5;
}
The above code is valid in C, but gives a redefinition error in C++.
My guess is that the C compiler treats the loop as if there is another scope inside the loop like below.
for (int i = 0; i < 10; ++i) {
{
int i = 5;
}
}
Why does the C compiler allow a second variable with the same name to be defined in the scope of the loop? Is there any particular reason or advantage for doing this?