Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to the use of switch statements in embedded software:

Rule 8.3.a.) The break for each case shall be indented to align with the associated case, rather than with the contents of the case code block.

Rule 8.3.b.) All switch statements shall contain a default block.

Example

switch (err)
{
   case ERR_A:
      ...
   break;

   case ERR_B:
      ...
   break;

   default:
      ...
   break;
}

Reasoning

Switch statements are powerful, but prone to errors such as missed break statements and unhandled cases. By aligning the case and break keywords it is possible to spot missing breaks.

Exceptions

None.

Enforcement

These rules can be enforced by an automated scan of all new or modified code during each build. Alternatively, they shall be enforced in code reviews.

Comments:

Does my code comply with the above rules if it has multiple case labels "stacked" one on top of the other, with no intervening code?

Rule 8.3.a says that each break must align with its paired case, but takes no position on whether or not all case statements require a break. Thus in the case (pun not intended) of a fall-through case you may wind up with rule-compliant code that looks like this:

switch (key_pressed)
{
    case 'A':
    case 'a':
        // Logic for handling these key presses here.
    break;

...

    default:
        // Default handler.
    break;
}

I use enums for case labels and intentionally avoid a final default clause when my intent is to ensure that each enum value is covered. Multiple compilers and static analysis tools will flag a missing case, a feature generally disabled by the presence of a default - and I always prefer build-time error detection to runtime detection! For this reason, the JSF C++ coding std (freely available online) discourages the default clause for these cases. As an aside, I also prefer C++ to C even if only used as a more typesafe C.

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.