Confused at Variable Scops

Hi
consider this Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream.h>
int x; //global variable


void main()
{
 int x; //local variable
 
 for(int x=0; x<10; x++)
 {
   cout<<"x in for="<<x;
   //how to access global x ?
   //how to access local x ?
 }
}

I know i can access to the global x with :: , but how should i access to the local x variable in the for?
I'm pretty sure there is no way to access the outer local x from inside the for loop.

Consider a case like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int x;
    {
        int x;
        {
            int x;
            {
                int x;
                //how would you possibly choose which x to use from here?
            }
        }
    }

    return 0;
}


Because shadowing can get this complicated, there is no mechanism for choosing a local variable other than the one with the smallest scope.
Last edited on
Also I noticed you are using void main() and <iostream.h> and I am guessing your compiler is quite old.
Consider getting a newer one (there are a lot of them free of charge).
thanks
when you do there is no .h iostream and main has to be type int
closed account (10oTURfi)
Level of uselessness: 100

If you are really into having dozens of integers of same name, put each in different namespace.
our teacher asked this question.
thanks anyway, i got it
Topic archived. No new replies allowed.