More bug-killing standards for firmware coding

Michael Barr

May 01, 2009

Michael BarrMay 01, 2009

In last month's column, I shared a set of 10 practical C coding standard rules for embedded software developers to reduce or eliminate bugs in their firmware. This month's installment provides five more such rules. If you only want the new rules, please jump ahead to the heading More Bug-Killing Coding Rules. First, I need to respond to one of the forum threads posted in response. This also gives me a chance to reiterate a key guiding principle behind the Netrino Embedded C Coding Standard.1

One true brace style?
On the subject of brace location, which I didn't even mention directly, a great discussion raged in the Embedded.com forum comparing the Allman brace style (which puts each brace on a line by itself) and the One True Brace Style (a.k.a., 1TBS, wherein the opening brace ends the prior line).

Forum discussion began with the bold assertion that "The Allman brace style should NEVER be used for languages that use braces for compound statements [and] a semicolon for terminating statements." I am quite comfortable with you adopting either style. However, one of the reasons given for 1TBS is something I cannot agree with. The discussion participant said that it's hard for human code reviewers to spot a mistake such as:

if (a == b);{    /* intended body of if statement */}

Though I agree it's possible for a human code reviewer to overlook this, the example precisely illustrates the importance of one of our guiding principles: "To be effective in keeping out bugs, coding standards must be enforceable. Wherever two or more competing rules would be similarly able to prevent bugs but only one of those rules can be enforced automatically, the more enforceable rule is recommended."

The above example is precisely the sort of bug we want our coding rules to prevent through automated testing. Rule #1 said "Braces ({ }) shall always surround the blocks of code (a.k.a., compound statements) following if, else, switch, while, do, and for keywords. Single statements and empty statements following these keywords shall also always be surrounded by braces." That is, an if (a == b); is broken every time by definition, ensuring that the static analysis warning is regarded as a rule violation by your team. This is true regardless of your choice for brace placement, so I won't share my personal preference here.

< Previous
Page 1 of 4
Next >

Loading comments...

Parts Search Datasheets.com

KNOWLEDGE CENTER