Plz look at this code

#include<iostream.h>

int x=0;

int main()
{
int x=1;
{
   int x=2;
   cout<<::x;
   
cout<<x;
}
return 0;
}

<< moderator edit: added [code][/code] tags >>

does anybody know how can i access main local variable x, from inside the block, without using pointers or references?

Recommended Answers

All 8 Replies

You could always just use better variable naming conventions. Using "x" for the name of every variable doesn't help you, and it doesn't help anybody looking at your code.

Well...this was the question asked to me in my viva exam...and i think having same name in different scopes makes the question more tricky

Your problem contains the ans.

cout<<::x;

I guess u didn't understood what i was asking.....i am not talking about the global variable ....iam talking about the local variable inside the main....but thanx anyways i was able to solve this problem

What's the solution? I mean how do you access the variable inside the main from the inner block?

you cant. watch.

int x=0; // global x
int main()
{
   int x=1; // main x
   {
       int x=2; // block x
       cout<< x<<endl; // prints block x
       cout<< ::x <<endl; // prints global x accessed with :: scope resolution operator
      // there is no way to access main x from here
   } // block x dies here
   cout<< x; // prints main x
   cout <<::x; // prints global x
   return 0;
}

The basic rule is a name in an inner scope hides the name in all outer scopes unless the scope resolution operator can be used to access it which is not possible with function scope local variables.

you cant. watch.

Yes you can

Here is the solution

#include<iostream.h>

int x=0;

int main()
{
int x=1;
{
   cout<<x;//access it before declaring variable in this local scope
   int x=2;
   cout<<::x;
   cout<<x   

}
return 0;
}

>Yes you can
Once you realize that it's a stupid trick question, of course. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.