In C/C++ why globals and static variables are initialized to default values.. why not leave it with just garbage values ? Any special reasons for this ?
views:
217answers:
3Because with the proper cooperation of the OS, 0 initializing statics and globals can be implemented with no runtime overhead.
Think about it, in the static realm you can't tell always for sure something is indeed initialized, or that main has started. There's also a static init and a dynamic init phase, the static one first right after the dynamic one where order matters.
If you didn't have zeroing out of statics then you would be completely unable to tell in this phase for sure if anything was initialized AT ALL and in short the C++ world would fly apart and basic things like singletons (or any sort of dynamic static init) would simple cease to work.
The answer with the bulletpoints is enthusiastic but a bit silly. Those could all apply to nonstatic allocation but that isn't done (well, sometimes but not usually).