19. Always initialize variables
Summary
Start with a clean slate: Uninitialized variables are a common source of bugs in C and C++ programs. Avoid such bugs by being disciplined about cleaning memory before you use it; initialize variables upon definition.
Discussion
In the low-level efficiency tradition of C and C++ alike, the compiler is often not required to initialize variables unless you do it explicitly (e.g., local variables, forgotten members omitted from constructor initializer lists). Do it explicitly.
There are few reasons to ever leave a variable uninitialized. None is serious enough to justify the hazard of undefined behavior.
If you’ve used a procedural language (e.g., Pascal, C, Fortran, or Cobol) you might be used to defining ...
Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.