重新定义的全局变量

Aym*_*nis 4 c global-variables local-variables

我有点困惑这个代码结果:

#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;
}
Run Code Online (Sandbox Code Playgroud)

为什么结果是10不是20?

jxh*_*jxh 6

局部变量g影响全局g.

如果你想要printf()显示20,你必须g使用你想要打印的全局变量的声明来遮蔽你的局部变量:

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;
}
Run Code Online (Sandbox Code Playgroud)


Ry-*_*Ry- 5

呼叫afunc改变全局g,并main保留其本地g.

输入函数不会将其范围与全局范围交换.每个函数*都有自己的范围.

*除其他事项外