How to access a global variable in the presence of local and global conflict

The 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 does someone want to do something beyond that? Why [a-zA-Z] *?

My answer would be: just to know that "this is possible."

Thank.

+5
source share
3 answers

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);
    }
}
+13
source
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 more complex problem is getting aif it is staticwith a file scope, but which is 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 */
}
+8
source

++, 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;
}
+4

All Articles