Static variable initialization?

Why the static variables are deterministically initialized and local variables aren’t?

See how the static variables are implemented. The memory for them is allocated at link time, and the initial value for them is also provided at link time. There is no runtime overhead.

On the other hand, the memory for local variables is allocated at run time. The stack has to grow. You don’t know what was there before. If you want, you can clear that memory (zero it), but that would incur a runtime overhead. The C++ philosophy is “you don’t pay for things you don’t use”, so it doesn’t zero that memory by default.

OK, but why are static variables initialized to zero, and not some other value?

Well, you generally want to do something with that variable. But then how do you know if it has been initialized? You could create a static boolean variable. But then it also has to be reliably initialized to something (preferably false). How about a pointer? You’d rather want it initialized to NULL than some random garbage. How about a struct/record? It has some other data members inside. It makes sense to initialize all of them to their default values. But for simplicity, if you use the “initialize to 0” strategy, you don’t have to inspect the individual members and check their types. You can just initialize the entire memory area to 0.

This is not really a technical requirement. The semantics of initialization could still be considered sane if the default value is something other than 0, but still deterministic. But then, what should that value be? You can quite easily explain why 0 is used (although indeed it sounds slightly arbitrary), but explaining -1 or 1024 seems to be even harder (especially that the variable may not be large enough to hold that value, etc).

And you can always initialize the variable explicitly.

And you always have paragraph 8.5.6 of the C++ standard which says “Every object of static storage duration shall be zero-initialized at program startup”.

For more info, please refer to these other questions:

Leave a Comment