c - 全局变量和局部变量混淆

标签 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 局部变量的作用域是否大于全局变量?

最佳答案

The output of printf is 20. but the local variable g = 10, so why it is printing 20 instead of 10

您没有更改局部变量。您在 main

中的行
g = 10;

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

关于c - 全局变量和局部变量混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997746/

相关文章:

c - 使用 select() 的非阻塞 I/O

将十进制数转换为二进制数

c - 尝试在 linux/include/linux/kvm_host.h 中查找 vm_list->vm_node 结构定义

c++ - 在不同的翻译单元中启动全局变量(涉及链接器)

从另一个程序控制 C 守护进程

c - 求数组 C 中数字的总和

javascript - 如何在javascript中访问函数外部的变量?

javascript - 不使用任何语句来声明变量是否正确?

c - 全局变量不能正常工作C

crystal-reports - Crystal 报表中的全局变量