全局变量和局部变量混淆

时间:2012-10-21 12:20:03

标签: c global-variables

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

int main(void)
{
     g = 10;    /* global 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;
}

printf的输出为20。 但局部变量g = 10, 那么为什么它打印20而不是10 局部变量的范围是否大于全局变量?

3 个答案:

答案 0 :(得分:3)

  

printf的输出是20.但局部变量g = 10,为什么呢   是打印20而不是10

您没有更改本地变量。您在main

中的行
g = 10;

正在改变全局变量。类似地,对afunc的函数调用会更改全局变量。您的整个程序只有一个变量g,这是全局变量。

答案 1 :(得分:3)

您的示例中没有名为g的局部变量。只有全球性的。所以输出是预期的。

如果你想要一个名为g的局部变量,试试这个:

int main(void)
{
     int g = 10;    /* local g, initialized with 10 */
     ...

通过上述内容,您现在有两个名为g的不同变量,其中一个变量仅在main中可见。

答案 2 :(得分:1)

因为您似乎没有实际声明新变量。你刚才提到过 g = 10;

您实际上并未定义新变量,只是引用了全局变量。希望这会有所帮助。

相关问题