C语言 为什么全局变量总是初始化为“0”,而不是局部变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14049777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are global variables always initialized to '0', but not local variables?
提问by yuvanesh
Possible Duplicate:
Why are global and static variables initialized to their default values?
可能的重复:
为什么全局变量和静态变量初始化为其默认值?
See the code,
看代码,
#include <stdio.h>
int a;
int main(void)
{
int i;
printf("%d %d\n", a, i);
}
Output
输出
0 8683508
Here 'a' is initialized with '0', but 'i' is initialized with a 'junk value'. Why?
这里“a”用“0”初始化,但“i”用“垃圾值”初始化。为什么?
回答by K-ballo
Because that's the way it is, according to the C Standard. The reason for that is efficiency:
因为根据C 标准,事情就是这样。这样做的原因是效率:
staticvariables are initialized at compile-time, since their address is known and fixed. Initializing them to
0does not incur a runtime cost.automaticvariables can have different addresses for different calls and would have to be initialized at runtimeeach time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.
静态变量在编译时初始化,因为它们的地址是已知和固定的。将它们初始化为
0不会产生运行时成本。自动变量对于不同的调用可以有不同的地址,并且必须在每次调用函数时在运行时初始化,从而产生可能不需要的运行时成本。如果您确实需要该初始化,则请求它。
回答by Raghu Srikanth Reddy
globaland staticvariables are stored in the Data Segment (DS) when initialized and block start by symbol (BSS)` when uninitialized.
global和static变量在初始化时存储在数据段 (DS) 中,未初始化时按符号 (BSS)` 块开始。
These variables have a fixed memory location, and memory is allocated at compile time.
这些变量有固定的内存位置,内存是在编译时分配的。
Thus globaland staticvariables have '0'as their default values.
因此global和static变量具有'0'它们的默认值。
Whereas autovariables are stored on the stack, and they do not have a fixed memory location.
而auto变量存储在堆栈中,并且它们没有固定的内存位置。
Memory is allocated to autovariables at runtime, but not at
compile time. Hence autovariables have their default value as garbage.
内存auto在运行时分配给变量,而不是在编译时。因此auto变量的默认值是垃圾。
回答by Jonathan Leffler
You've chosen simple variables, but consider:
您选择了简单变量,但请考虑:
void matrix_manipulation(void)
{
int matrix1[100][100];
int matrix2[100][100];
int matrix3[100][100];
/* code to read values for matrix1 from a file */
/* code to read values for matrix2 from a file */
/* code to multiply matrix1 by matrix2 storing the result in matrix3 */
/* code to use matrix3 somehow */
}
If the system initialized the arrays to 0, the effort would be wasted; the initialization is overwritten by the rest of the function. C avoids hidden costs whenever possible.
如果系统将数组初始化为0,那么工作就白费了;初始化被函数的其余部分覆盖。C 尽可能避免隐藏成本。
回答by WiSaGaN
Global variables are allocated and initialized before the mainfunction starts, while local variables are generated on the stack as the instance of the program runs.
全局变量在main函数启动之前分配和初始化,而局部变量在程序实例运行时在堆栈上生成。

