#7. Always initialize variables

Variables should be initialized with a known and meaningful value as soon as they are created. A variable should never begin to exist without having a known value.

The most common sign I've found that someone is a novice C++ programmer are uninitialized variables. You look at a function body and you see the definitions of many uninitialized variables, usually grouped at the beginning of the function. Sometimes they are assigned a value later; sometimes they aren't used at all; and sometimes they are used without having been initialized, causing unpredictable behaviour.

This is bad. Very bad. It hurts readability and it is error prone. The risk of using the value of an uninitialized variable is never worth taking. Don't do it. Always initialize variables.

Bibliography

[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book discusses the initialization of variables in Section 10.3, "Guidelines for initializing variables".

[Sutter-Alexandrescu 2004]
Herb Sutter, Andrei Alexandrescu: C++ Coding Standards. 101 Rules, Guidelines and Best Practices, Addison Wesley, 2004.

This book includes this recommendation as its rule 19, "Always initialize variables" (page 36).

Comments

Post a Comment

Popular posts from this blog

#2. Make all type conversions explicit

Welcome to The Deep Blue C++

#13. Organize your code in classes