DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Scope Problem (http://www.daniweb.com/forums/thread32212.html)

SpS Sep 13th, 2005 4:57 am
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?

chrisbliss18 Sep 13th, 2005 5:19 am
Re: Scope Problem
 
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.

SpS Sep 13th, 2005 8:55 am
Re: Scope Problem
 
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

Paul.Esson Sep 17th, 2005 7:35 am
Re: Scope Problem
 
Your problem contains the ans.

Quote:

cout<<::x;

SpS Sep 18th, 2005 9:14 am
Re: Scope Problem
 
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

aminura Sep 25th, 2005 8:57 am
Re: Scope Problem
 
What's the solution? I mean how do you access the variable inside the main from the inner block?

Stoned_coder Sep 25th, 2005 9:13 am
Re: Scope Problem
 
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.

SpS Sep 25th, 2005 9:20 am
Re: Scope Problem
 
Quote:

Originally Posted by Stoned_coder
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;
}

Narue Sep 25th, 2005 10:51 am
Re: Scope Problem
 
>Yes you can
Once you realize that it's a stupid trick question, of course. ;)


All times are GMT -4. The time now is 2:34 pm.

Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC