C 中允许重新声明全局变量?
Redeclaration of global variables allowed in C?
为什么 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;
是声明。
int x = 2;
是定义(也是声明)。
只要声明兼容(相同),就允许重新声明。
int x;
int x;
会起作用的。不允许重新定义
int x = 2;
int x = 2;
不会工作。
不允许在没有声明或没有定义的情况下使用
int x;
,在文件范围内,是一个 暂定定义 以及 @PSkocik 的回答,如果定义初始化不存在。
I have previously thought that int x
at global scope is equivalent to int x = 0
.
关于 "global" int x;
的棘手部分是假设它用 0 初始化。如果 any 中不存在另一个 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 中允许使用此代码?
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;
是声明。
int x = 2;
是定义(也是声明)。
只要声明兼容(相同),就允许重新声明。
int x;
int x;
会起作用的。不允许重新定义
int x = 2;
int x = 2;
不会工作。
不允许在没有声明或没有定义的情况下使用
int x;
,在文件范围内,是一个 暂定定义 以及 @PSkocik 的回答,如果定义初始化不存在。
I have previously thought that
int x
at global scope is equivalent toint x = 0
.
关于 "global" int x;
的棘手部分是假设它用 0 初始化。如果 any 中不存在另一个 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;