Natsu Natsu - 3 months ago 11
C++ Question

Why am I not getting an error?

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 variables
i
. 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.

Answer

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;
    }
}