Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefined Global variable

I'm a little Confused about this code result:

#include <stdio.h>
int g;
void afunc(int x)
{
     g = x; /* this sets the global to whatever x is */
}

int main(void)
{
    int g = 10;    /* Local g is now 10 */
    afunc(20); /* but this function will set it to 20 */
    printf("%d\n", g); /* so this will print "20" */

    return 0;
}

Why the result is 10 Not 20 ?

like image 575
Ayman Younis Avatar asked Dec 06 '22 06:12

Ayman Younis


2 Answers

The local variable g shadows the global g.

If you want the printf() to show 20, you have to shadow your local variable g with a declaration of the global one you want to print:

int main(void)
{
    int g = 10;            /* Local g is now 10 */
    afunc(20);             /* Set global g to 20 */
    printf("%d\n", g);     /* Print local g, "10" */
    {
        extern int g;      /* Use global g */
        printf("%d\n", g); /* Print global g, "20" */
    }
    return 0;
}
like image 116
jxh Avatar answered Dec 14 '22 23:12

jxh


Calling afunc changes the global g, and main retains its local g.

Entering a function doesn’t swap its scope with the global scope. Each function* has its own scope.

* Among other things

like image 44
Ry- Avatar answered Dec 15 '22 00:12

Ry-