7.2.a. All variables shall be initialized before use.

7.2.b. It is preferable to define local variables as you need them, rather than all at the top of a function.

7.2.c. If project- or file-global variables are used, their definitions shall be grouped together and placed at the top of a source code file.

7.2.d. Any pointer variable lacking an initial address shall be initialized to NULL.


uint32_t  g_array[NUM_ROWS][NUM_COLS] = { ... };

    for (int col = 0; col < NUM_COLS; col++)
        g_array[row][col] = ...;

Reasoning: Too many programmers assume the C run-time will watch out for them, e.g., by zeroing the value of uninitialized variables on system startup. This is a bad assumption, which can prove dangerous in a mission-critical system. For readability reasons it is better to declare local variables as close as possible to their first use,12 which C99 makes possible by incorporating that earlier feature of C++.

Enforcement: An automated tool shall scan all of the source code prior to each build, to warn about variables used prior to initialization; static analysis tools can do this. The remainder of these rules shall be enforced during code reviews.


[12] [Uwano] describes back-and-forth code review eye movements that demonstrate the value of placing variable declarations as close as possible to the code that first references them.


Does Rule 7.2.a mean that variables must be initialized where they are declared? I've seen where some coding standards require this, but for some variables there is no single meaningful initial / default value and I thus like to initialize those variables inside an if statement or similar.

Does Rule 7.2.b mean that variables should be declared immediately before their first usage?

Rule 7.2.a only requires the initialization be before the first use. Thus a variable may or may not be initialized at its declaration specifically. I agree with you that sometimes the best place to initialize it is not until sometime after the definition.

Rule 7.2.b states only a preference toward placing definitions immediately prior to the first use of the variable. Follow this rule when possible (i.e., compiler-supported) and doing so will not make the program harder to read or maintain. Hopefully that makes things clearer.