Reputation: 111
It baffles me why C++ compilers do not initialise every integer declaration to 0, be it local or global or members? Why do uninitialised sections exists in the memory model?
Upvotes: 1
Views: 447
Reputation: 76785
I know it's a dull answer, but your question begs for it exactly:
Because the C++ standard says so.
Why does it say so? Because C++ is built on a principle:
Don't pay for what you don't use.
Setting memory to a certain value costs CPU time and memory bandwidth. If you want to do it, do it explicitly. A variable declaration should not incur this cost.
Upvotes: 17
Reputation: 69723
C++ is based on C, and in C a primary design concern was code efficiency. In most cases you want to initialize a new variable to a specific value after declaring it. When the compiler would write 0 to that memory address just to write another value to it shortly afterwards, it would be a waste of a CPU cycle.
Sure, a smart compiler could detect that a variable isn't read before it gets a value assigned and could optimize the initialization to 0 away. But when C was developed, compilers weren't that smart yet.
The C language and its standard library generally follow the principle that it doesn't do stuff automatically when it might be unnecessary to do it under some circumstances.
Upvotes: 7
Reputation: 19282
It might make life easier for you if it did, but C++ errs on the side of avoiding overheads, e.g. setting values which you might then reset to something else.
Upvotes: 2