为什么 C 中允许使用此代码?
int x;
int main() {
printf("%d\n", x);
return 0;
}
int x = 2;
它使用 -Wall -std=c89
与 gcc
和 clang
编译时没有警告。
我之前认为 int x
在全局范围内等同于 int x = 0
。我发现自己很惊讶。
最佳答案
int x;
,在文件范围内,是一个暂定定义,并由@PSkocik 回答。如果不存在具有初始化的定义,将像 int x = 0;
那样工作。
I have previously thought that
int x
at global scope is equivalent toint x = 0
.
关于“全局”int x;
的棘手部分是假设它用 0 初始化。如果另一个 int x = constant;
没有初始化它,它就用 0 初始化存在于任何编译单元中。
因此建议在对象需要初始化时显式初始化,不要指望默认初始化为 0 位。
// Does an initialization exist, in some file -maybe?
int x;
// Better. If another file initializes `x`, good to see a compiler/linker error.
int x = 0;
关于c - C 中允许重新声明全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075079/