Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a variable which is neither global nor local?

Tags:

c++

scope

Look at this piece of code

int x = 1;
int main(int argc, char* argv[])
{
 int x = 2;
 {
  int x = 3;
  cout << x << endl;
  cout << ::x;
 }

getch();
    return 0;
}

When i call x from within the block i'm getting 3. When i call ::x i'm getting 1. Is it possible to call x equal to 2 from within the block?

like image 932
Andrey Chernukha Avatar asked Dec 11 '11 17:12

Andrey Chernukha


2 Answers

With cheating:

int x = 1;
int main(int argc, char* argv[])
{
    int x = 2;
    {
      int& ox = x;
      int x = 3;
      cout << x << endl;
      cout << ::x << endl;
      cout << ox << endl;
    }

    getch();
    return 0;
}
like image 109
Xeo Avatar answered Sep 23 '22 06:09

Xeo


No, it's not possible to do that.

like image 33
Oliver Charlesworth Avatar answered Sep 26 '22 06:09

Oliver Charlesworth