tags:

views:

142

answers:

6
#include <iostream>
using namespace std;

int main() {
    int i;
    for(i=0; i <= 11; i+=3)
        cout << i;
    cout << endl << i << endl;
}

output is: 0 3 6 and 9 and then once it exits the loop its 12. The addresses of i inside the loop and out appear the same

What I need to know is: Is the i inside the for loop the same as the i that was initialized outside the for loop because the variable i was first initialized before the for loops i was ever created?

+10  A: 

Yes, the i inside the loop is the same as the i outside of the loop because you've only declared it once.

If for some reason you want it to be different (which I highly recommend against, you should choose different names for different variables) you could redeclare the i in the for loop:

for (int i = 0; i ...
dash-tom-bang
+1  A: 

There is only one 'i' variable. You're just assigning a value in the foor loop.

vash47
+1  A: 

There is only one variable extant here - and yes, the i inside the loop is the same as the one you output after exiting the loop. However the variable was only initialized as part of the loop, not before.

Steve Townsend
+3  A: 

It's de same 'i' var

#include <iostream>
using namespace std;

int i = 0;

int main() {
    int i;
    for(i=0; i <= 11; i+=3)
        cout << i;
    cout << endl << i << endl;
    cout << endl << ::i << endl;
}

i is 12

::i is 0

HarzIce
That makes a lot more sense to me, thanks.
John
Nicely explained!
AJ
+2  A: 

In order to create a new object (variable) in C++ (as well as in C) you have to explicitly define it. In your program you have one and only one variable definition - int i;. That immediately means that there's one and only one variable i there. There's no chance for any other i, regardless of any "scopes of for loop" or anything else.

AndreyT
A: 

A for-loop of the form:

for (init condition; expression) statement

Is exactly equivalent to:

{
    init
    while (condition)
    {
        statement
        expression;
    }
}

So with your code:

    int i;
    {
        i=0;
        while (i <= 11)
        {
            cout << i;
            i += 3;
        }
    }
    cout << endl << i << endl;
}

Can you tell now? Andrey puts it best: if you didn't define it, it doesn't exist.

GMan