You can define variables with the same names in different scopes. The first variable i
is defined in the scope of the main
function. In the loop there is another implied nested and anonymous scope for the variables you declare for the loop.
For the compiler, the code
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
is more or less equivalent to
{
int i;
for(i = 1; i <= 10; i++)
{
cout << i << endl;
}
}
2
solved Why am I not getting an error?