重新定义全局变量 [英] Redefined Global variable

查看:74
本文介绍了重新定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此代码结果我有些困惑:

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

为什么结果是10而不是20?

Why the result is 10 Not 20 ?

推荐答案

调用 afunc 会更改全局 g ,而 main 保留其本地 g .

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.

*除其他外

这篇关于重新定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆