-6

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.

Natsu
  • 71
  • 1
  • 7
  • 1
    You can declare variables with the same name in distinct scopes. `for()` starts a new scope. – πάντα ῥεῖ Aug 13 '16 at 08:31
  • So would a variable declared outside the for() not be usable inside it? But we can. For example: `int j = 0; for(into i = 1; i < 5; i++){j++;}` would be perfectly valid but is it differentiating between the two i variables in my program? – Natsu Aug 13 '16 at 08:48
  • Sure you can do that. Just omit the declaration in the first part of the `for()` loop like: `for(i = 1;`. – πάντα ῥεῖ Aug 13 '16 at 08:50
  • Don't use `std::endl` unless you need the extra stuff that it does. `'\n'` ends a line. – Pete Becker Aug 13 '16 at 11:37

1 Answers1

3

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;
    }
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • But wouldn't this still lie in the scope of the main() function? For example when we declare a variables outside of the main() function its scope is the whole program. So wouldn't declaring a variable inside the main() make its scope the whole of the main() function and thus wouldn't the two variable clash? – Natsu Aug 13 '16 at 08:45
  • @Natsu DEfining a variable in a nested scope *hides* the previous variable declaration. In the nested scope, the previous variable will be unavailable. You can even define the nested scopes variable to be of a completely different type. Any [beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) would have told you this. – Some programmer dude Aug 13 '16 at 08:50