Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to variable initialization in embedded software:

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

Rule 7.2.b.) It is preferable to create variables as you need them, rather than all at the top of a function. (Yet another handy feature allowed by [C99] but not in [C90].)

Example

for (int loop = 0; loop < MAX_LOOPS; loop++)
{
    ...
}

Reasoning

Too many programmers assume the C run-time will watch out for them. This is a very bad assumption, which can prove dangerous in a real-time system. It is easier to initialize some variables closer to their use, and this also aids readability of the code. (Note: One study of back-and-forth eye movements during code reviews ([Uwano]) demonstrated the importance of placing variable declarations as close as possible to the code that uses them.

Exceptions

None.

Enforcement

An automated tool shall scan all of the source code prior to each build, to warn about variables used prior to initialization. Lint is an example of a tool that can do this well.

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 a bit after the declaration.

Rule 7.2.b states only a preference toward placing declarations 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 today!

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.