众所周知,外部声明的变量可以被初始化。
#include<stdio.h>
extern int a=5; //will work as both definition and declaration.
int main()
{
}
<小时/>
为什么这个程序编译和运行没有错误。
extern int a=5; //will work as both definition and declaration.
int main()
{
}
int a; // isn't it second definition??
最佳答案
C 有一个“暂定定义”的概念。大多数没有初始值设定项的定义都是“暂定的”,因此允许任意数量的定义,只要它们不相互冲突即可。在翻译单元的末尾,变量的定义基本上变成了这些定义的组合(例如,如果一个定义说变量是 const,而另一个定义说它是 volatile),该变量最终将同时为 const
和 volatile
。
带有初始值设定项的定义绝不是临时性的,因此只允许其中之一。
关于c - 变量的双重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284682/