Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 278
VishalDevgire Avatar asked Mar 10 '13 20:03

VishalDevgire


2 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);
    }
}
like image 107
cnicutar Avatar answered Oct 04 '22 03:10

cnicutar


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 */
}
like image 26
R.. GitHub STOP HELPING ICE Avatar answered Oct 04 '22 03:10

R.. GitHub STOP HELPING ICE