embedded software boot camp

Coding Standard Rule #1: Always Use Braces

Thursday, March 19th, 2009 by Michael Barr


This is the first in a planned series of blog posts suggesting how to reduce firmware bugs by following a set of simple C programming rules.

Rule: 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.

Example (don’t):
if (timer.done)
// A single statement needs braces!
timer.control = TIMER_RESTART;

Example (do):
while (!timer.done)
{
// Even an empty statement should be surrounded by braces.
}

Reasoning: There is considerable risk associated with the presence of empty statements and single statements that are not surrounded by braces. Code constructs of this type are often associated with bugs when nearby code is changed or commented out. This type of bug is entirely eliminated by the consistent use of braces.

Coding Standard #2

These rules are excerpts from the Embedded C Coding Standard book.

Tags: , , , ,

One Response to “Coding Standard Rule #1: Always Use Braces”

  1. Allen Moore says:

    This is required by Rule 14.8 in MISRA-C (2004). I think most folks could much improve their coding just by trying to follow the MISRA guidelines. If you don’t have a coding standard already, this is a good place to start.

Leave a Reply