954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Scope Problem

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?

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

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.

chrisbliss18
Posting Shark
917 posts since Aug 2005
Reputation Points: 38
Solved Threads: 25
 

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

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

Your problem contains the ans.

cout<<::x;
Paul.Esson
Junior Poster
181 posts since Feb 2005
Reputation Points: 21
Solved Threads: 10
 

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

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

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

aminura
Light Poster
47 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 

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.

Stoned_coder
Junior Poster
164 posts since Jul 2005
Reputation Points: 19
Solved Threads: 5
 
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;
}
SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

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

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You