Global variable ,static always initialized but auto is not initialized
- 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.
- Reproducibility: leaving the values alone would make program behavior non-repeatable, making bugs really hard to find.
- Elegance: it’s cleaner if programs can start from 0 without having to clutter the code with default initializers.
One might wonder why the auto
storage class does start as garbage. The answer is two-fold:
- It doesn’t make a sense. The very first stack frame does receive zero values. The garbage, or uninitialized values that subsequent instances at the same stack level see are really the previous values left by the same program.
- There might be a runtime performance penalty associated with initializing
auto
(function locals) to anything. A function might not use any or all of a large array, say, and it could be invoked thousands or millions of times. The initialization of static and global only needs to happen once.