How to access global variable when there is a local and global conflict

15,280

Solution 1

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);
    }
}

Solution 2

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 */
}

Solution 3

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;
}
Share:
15,280
VishalDevgire
Author by

VishalDevgire

I like learning new programming languages, watching anime and playing video games. "Nature of human intellect is such that it can't stay still... always in search for distractions just to ignore the obvious."

Updated on June 12, 2022

Comments

  • VishalDevgire
    VishalDevgire almost 2 years

    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.

  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE about 11 years
    +1 for beating me by 30 seconds.
  • Heisenbug
    Heisenbug about 11 years
    +1: nice trick..didn't know about that.
  • cnicutar
    cnicutar about 11 years
    @R.. To be fair, I think I first saw it some time ago in one of your older posts.
  • Grijesh Chauhan
    Grijesh Chauhan about 11 years
    @cnicutar when would you prefer to access via pointer compare to extern keyword ? I think it will work for global static variable too. correct ?
  • cnicutar
    cnicutar about 11 years
    @GrijeshChauhan I think it's best to avoid name collisions in the first place, by defensively naming objects and functions your code exports (i.e. everything not static). On the other hand, if you already have a pointer there's no need for this trick.
  • ad absurdum
    ad absurdum over 6 years
    Why not just do int b = a; int a = 40;? Or, might the compiler reorder the lines in this case....
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 6 years
    Indeed you could do that.
  • void
    void almost 5 years
    it didn't work, I'm using DigitalMars compirer