Barr Group TwitterBarr Group Vimeo

Rules:

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.

Example:

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.


Footnotes

[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.

Comments:

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.

What’s happening and how it’s done. Get in the know.

Sign Up for Our Newsletter

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.