5

Code :

int a = 33;
int main()
{
  int a = 40; // local variables always win when there is a conflict between local and global.
  // Here how can i access global variable 'a' having value '33'.
}

If you ask : Why would someone want to do above thing? Why [a-zA-Z]* ?

My answer would be : Just to know that 'it is possible to do so'.

Thanks.

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59

3 Answers3

15

How about this old trick:

int main()
{
    int a = 40; // local variables always win when there is a conflict between local and global.

    {
        extern int a;
        printf("%d\n", a);
    }
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392
11
int a = 33;
int main()
{
  int a = 40;
  int b;
  {
    extern int a;
    b = a;
  }
  /* now b contains the value of the global a */
}

A harder problem is getting a if it's static with file scope, but that's also solvable:

static int a = 33;
static int *get_a() { return &a; }
int main()
{
  int a = 40;
  int b = *get_a();
  /* now b contains the value of the global a */
}
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
4

IT IS C++, I OVERLOOKED C tag, SORRY !

int a = 100;

int main()
{
    int a = 20;

    int x = a; // Local, x is 20

    int y = ::a; // Global, y is 100

    return 0;
}
masoud
  • 55,379
  • 16
  • 141
  • 208