问题描述
在 C/C++ 中,为什么将全局变量和静态变量初始化为默认值?
In C/C++, why are globals and static variables initialized to default values?
为什么不留下垃圾值呢?有没有什么特别的这是什么原因?
Why not leave it with just garbage values? Are there any special reasons for this?
推荐答案
安全性:不理会内存会泄漏来自其他进程或内核的信息.
Security: leaving memory alone would leak information from other processes or the kernel.
效率:这些值在初始化之前是无用的,并且在具有展开循环的块中将它们归零更有效.操作系统甚至可以在系统空闲时将空闲列表页面归零,而不是在某些客户端或用户等待程序启动时.
Efficiency: the values are useless until initialized to something, and it's more efficient to zero them in a block with unrolled loops. The OS can even zero freelist pages when the system is otherwise idle, rather than when some client or user is waiting for the program to start.
可重复性:不考虑值会使程序行为不可重复,从而很难找到错误.
Reproducibility: leaving the values alone would make program behavior non-repeatable, making bugs really hard to find.
优雅:如果程序可以从 0 开始,而无需使用默认初始化程序将代码弄乱,那就更简洁了.
Elegance: it's cleaner if programs can start from 0 without having to clutter the code with default initializers.
然后有人可能会想为什么 auto
存储类确实 开始时是垃圾.答案有两个:
One might then wonder why the auto
storage class does start as garbage. The answer is two-fold:
它没有,在某种意义上.每个级别的第一个堆栈帧页面(即,添加到堆栈的每个新页面)确实接收零值.相同堆栈级别的后续函数实例看到的垃圾"或未初始化"值实际上是您自己程序及其库的其他方法实例留下的先前值.
It doesn't, in a sense. The very first stack frame page at each level (i.e., every new page added to the stack) does receive zero values. The "garbage", or "uninitialized" values that subsequent function instances at the same stack level see are really the previous values left by other method instances of your own program and its library.
可能会有二次(或其他)运行时性能损失与将 auto
(函数局部变量)初始化为任何内容相关联.例如,在任何给定的调用中,一个函数可能不会使用任何或全部大型数组,并且它可能会被调用数千或数百万次.静态和全局变量 OTOH 的初始化只需要发生一次.
There might be a quadratic (or whatever) runtime performance penalty associated with initializing auto
(function locals) to anything. A function might not use any or all of a large array, say, on any given call, and it could be invoked thousands or millions of times. The initialization of statics and globals, OTOH, only needs to happen once.
这篇关于为什么将全局变量和静态变量初始化为其默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!