C++: scope of for loop?
#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?
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 ...
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
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.
There is only one 'i' variable. You're just assigning a value in the foor loop.
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.
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.
精彩评论