In the following program:
#include <iostream>
using namespace std;
int main(){
int i = 99;
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
cout << endl << endl;
cout << i << endl;
return 0;
}
I am not getting an error on compilation.
My question is why this is happening.
The int
variable i
was declared twice. The first time i
was declared in the main()
function and thus its scope will be this whole main()
function including the for
loop. The second time i
was declared with the for
loop and thus its scope will be only the for
loop. So, now inside the scope of the for
loop there exists two int variablesi
. Shouldn't this be a cause of error? And if not why?
Second thing is the output I am getting:
1
2
3
4
5
6
7
8
9
10
99
I also don't understand the output. Why after the execution of the for
loop, the value of i
that is being printed is 99 and not 10.