design – Why does the C++ standard still allow uninitialized primitive variables?

(…) so that objects of primitive type (int, unsigned, float, double, bool, char) get default-initialized to 0? Wouldn’t this prevent an entire class of typical beginner mistakes?

I don’t think so. Usually the actual mistake is that the programmer either assumed the variable would be initialized to something useful after the declaration, or simply forgot to init it right there.

In many cases forcing zero initialization would only mask the problem. 0 is a valid value for all of the fundamental types but that doesn’t imply it’s useful and semantically valid for the use case in question. Consider:

/* Just for demonstration! This is BAD code! */

int result;  // uninitialized

// The function is supposed to initialize `result` to >=1 using an out parameter.
// But it’s buggy and doesn’t touch `result` at all.

// `result` is read here in some way.

Currently reading result at the end is undefined behaviour. Forced zero init wouldn’t improve the situation because the variable still does not contain a semantically valid value. It’s expected to hold a value greater than 0, after all. The error is just masked and likely to lead to problems later in the execution of the program. That’s very similar to undefined behaviour.

I can’t speak for the C++ committee, of course. And I cannot look into the mind of the C++ community as a whole. But I guess this is at least one important part of the reason why forced zero init isn’t considered as a change to the language – “you don’t pay for what you don’t use” being another important part.

Imo a better, although ultimately just as hopeless, idea would be to disallow uninitialized variables altogether. That would solve the problem, but would also be a backwards incompatible change to a commonly used feature. A proposal that’s guaranteed to break a vast amount of existing code is highly unlikely to make it into the standard.

What’s left is static and dynamic code analysis to detect such bugs.