Redefined Global variable

*爱你&永不变心* 提交于 2021-02-04 15:54:24

问题


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 ?


回答1:


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




回答2:


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



回答3:


If you get rid of the int in

int g = 10;

then main will also be referring to the same global variable as afunc is.

This is called variable shadowing




回答4:


Have NOT modified your code, but have adjusted your comments to indicate what the code is doing. By the way, commenting your code is a really good idea and makes for better lab scores!! signed, A Former Graduate TA

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

int main(void)
{
    int g = 10;    /* Define and set a Local g to 10 */
    afunc(20);     /* This function sets global x to 20 */
    printf("%d\n", g); /* this prints local g "10" */

    return 0;
}

To think about this "look-up" from main to global storage. You see local g before global g, thus local g is used.




回答5:


In both the occasions, though the variable name appears to be same, they 2 are referring 2 different memory area. The variable g declared outside any function got stored in the RAM memory area, and the variable g declared inside main is got stored in stack area. So the invocation of afunc() is changing the variable g stored in RAM but again printing the variable g(stored in stack) which got declared locally.



来源:https://stackoverflow.com/questions/18114633/redefined-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!