为什么全局变量总是初始化为“0",而不是局部变量? [英] Why are global variables always initialized to '0', but not local variables?
问题描述
可能的重复:
为什么将全局和静态变量初始化为默认值值?
查看代码,
#include <stdio.h>
int a;
int main(void)
{
int i;
printf("%d %d
", a, i);
}
输出
0 8683508
这里的a"用0"初始化,但i"用垃圾值"初始化.为什么?
Here 'a' is initialized with '0', but 'i' is initialized with a 'junk value'. Why?
推荐答案
因为根据 C 标准,事情就是这样.这样做的原因是效率:
Because that's the way it is, according to the C Standard. The reason for that is efficiency:
static 变量在编译时初始化,因为它们的地址是已知和固定的.将它们初始化为
0
不会产生运行时成本.
static variables are initialized at compile-time, since their address is known and fixed. Initializing them to
0
does not incur a runtime cost.
自动变量对于不同的调用可以有不同的地址,并且必须在每次调用函数时在运行时初始化,从而产生运行成本不需要.如果您确实需要初始化,请请求它.
automatic variables can have different addresses for different calls and would have to be initialized at runtime each time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.
这篇关于为什么全局变量总是初始化为“0",而不是局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!