c++ - Why are global and static variables initialized to their default values? -
in c/c++, why globals , static variables initialized default values?
why not leave garbage values? there special reasons this?
security: leaving memory alone leak information other processes or kernel.
efficiency: values useless until initialized something, , it's more efficient 0 them in block unrolled loops. os can 0 freelist pages when system otherwise idle, rather when client or user waiting program start.
reproducibility: leaving values alone make program behavior non-repeatable, making bugs hard find.
elegance: it's cleaner if programs can start 0 without having clutter code default initializers.
one might wonder why auto
storage class does start garbage. answer two-fold:
it doesn't, in sense. first stack frame page @ each level (i.e., every new page added stack) receive 0 values. "garbage", or "uninitialized" values subsequent function instances @ same stack level see previous values left other method instances of own program , library.
there might quadratic (or whatever) runtime performance penalty associated initializing
auto
(function locals) anything. function might not use or of large array, say, on given call, , invoked thousands or millions of times. initialization of statics , globals, otoh, needs happen once.
Comments
Post a Comment