Page 1 of 1

Out of Scope?

Posted: Wed Nov 26, 2008 9:25 pm
by XianForce
Well I was reading my Sams Teach Yourself C++ in an Hour a Day and one of the questions asked this:

What is the value of x when the for loop completes?

Code: Select all

for (int x = 0; x < 100; x++)
I thought it would be 100, because the first statement it defines and initializes the variable, so I would think it should be 100.

The answer in the book says: "The variable is out of scope and thus has no valid value"

I'm a little confused by this. Is this just meaning after the for loop completely ends? or the final value of x?

My best guess is the variable was created within the loop so once the loop ends, its out of scope, and the question is referring to after the loop ends.

Re: Out of Scope?

Posted: Wed Nov 26, 2008 9:29 pm
by avansc
yes, any variables inside loops are just local to that loop

so if you were to do

for(int a = 0;a< 100;a++)
{
}

int x = a;

you would get an error.

however

int a = 0;
for(a;a<100;a++)
{
}
int x = a;

that will work.

Re: Out of Scope?

Posted: Wed Nov 26, 2008 9:31 pm
by XianForce
avansc wrote:yes, any variables inside loops are just local to that loop

so if you were to do

for(int a = 0;a< 100;a++)
{
}

int x = a;

you would get an error.

however

int a = 0;
for(a;a<100;a++)
{
}
int x = a;

that will work.

Ok, so my last statement was right?

Re: Out of Scope?

Posted: Wed Nov 26, 2008 9:44 pm
by avansc
yup

Re: Out of Scope?

Posted: Wed Nov 26, 2008 10:11 pm
by XianForce
avansc wrote:yup
Alright thank you :mrgreen:

Re: Out of Scope?

Posted: Thu Nov 27, 2008 11:39 pm
by MarauderIIC
Just for fun...

Code: Select all

int a = 100;
{
    int a = 50;
    cout << a << endl;
}
cout << a << endl; //this a is not that a :)

Re: Out of Scope?

Posted: Fri Nov 28, 2008 12:17 am
by XianForce
MarauderIIC wrote:Just for fun...

Code: Select all

int a = 100;
{
    int a = 50;
    cout << a << endl;
}
cout << a << endl; //this a is not that a :)

Easy, there are 2 variables named a with this one. You declared a new a within the brackets so it would display 50, but after the brackets end, that a would go out of scope. Thus, a would still equal 100.