为什么总是被初始化为“0”的全局变量,而不是局部变量? [英] Why are global variables always initialized to '0', but not local variables?

查看:985
本文介绍了为什么总是被初始化为“0”的全局变量,而不是局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:

  <一href=\"http://stackoverflow.com/questions/2091499/why-global-and-static-variables-are-initialized-to-their-default-values\">Why在全局和静态变量初始化为默认值吗?

查看code,

#include <stdio.h>

int a;
int main(void)
{
    int i;
    printf("%d %d\n", a, i);
}

输出

0 8683508

下面'一'被初始化为'0',而是'我'与'垃圾值初始化。为什么呢?

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:


  • 静态的变量初始化时的编译时间的,因为他们的地址是已知的和固定的。它们初始化为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆