How we change what others think, feel, believe and do
CHAPTER 9 : Data Usage
9.12 Initializing variables
Uninitialized variables are a common causes of unpleasant problems, for example where the random value that they contain only causes problems when it is zero. This type of bug can be very difficult to find!
The decision on where in the code to initialize a variable can affect the understanding of its use, and consequently may prevent associated problems from occurring. There are several common approaches:
9.12.1 Initializing at the declaration point
The earliest place that a variable can be initialized is at its point of definition:
int DangerState = OK; /* not OK = unsafe for humans */
This simplifies the code by putting everything in one place. When you ask "What is 'DangerState'?", and look back to the definition for clues, you find its initial value as well as its type and any comment about it.
Note that this usage is limited to where the initializer is a constant. The layout can also make the block of data declarations appear untidy (although a 'comb' layout could help this). Confusion may also be caused if the variable is re-initialized between the definition point and the current point of usage.
9.12.2 Initializing at the start of the function code
A common place to initialize variables is at the start of the function, just after data definitions. This effectively forms a part of the 'context':
int DangerState; /* not OK = unsafe for humans
This is effectively an extension of initializing at the point of definition, but which allows the variable to be initialized with a non-constant value. The initial value of variables can still be easily found, although the separation of the points of initialization and of usage of the variable can still cause confusion and hazard.
9.12.3 Initialize just before usage
It is effectively applying the principle of minimizing scope if the variable is initialized just before it is used:
int DangerState; /* not OK = unsafe for
The scope and usage of the variable is now clearer, although the initialization line does add slightly to the complexity of the code around its usage.
A further alternative is to include initialization in for statements (see 8.5 for discussion).
9.12.4 Initializing static data
Static variables are automatically initialized to zero in C. It is clearer to always explicitly initialize them.
And the big