Skip to main content


Showing posts from May, 2014

#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".