【发布时间】:2015-03-18 08:28:31
【问题描述】:
当跨文件定义同名全局变量时,内存中实际上只定义了一个变量的实例。例如 int temp 在 a.c、b.c 和 main.c 中定义,当我检查变量的地址时,它们在所有文件中都是相同的。
现在变量在没有使用说明符extern的情况下得到扩展,那么extern有什么用呢?
文件交流
int temp;
a()
{
temp = 10;
printf("the value of temp in a.c is %d\n",temp);
}
文件 b.c
int temp;
b()
{
temp = 20;
printf("the value of temp in b.c is %d\n",temp);
}
文件 main.c
int temp;
main()
{
temp = 30;
a();
b();
printf("the value of temp in main.c is %d\n",temp);
}
o/p 是
the value of temp in a.c is 10
the value of temp in b.c is 20
the value of temp in main.c is 20.
在上述情况下,main.c 中的 temp 的值也是 20,因为它在 b.c 中发生了变化,并且反映了最新的值。 为什么变量 temp 得到扩展而不创建 3 个不同的变量?
【问题讨论】:
标签: c scope global-variables extern