Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to if-else statements:

Rule 8.2.a.) The shortest (measured in lines of code) of the if and else if clauses should be placed first. (Note: Thanks to [Holub] for putting this “formatting for readability” idea into words.)

Rule 8.2.b.) Nested if-else statements shall not be deeper than two levels. Use function calls or switch statements to reduce complexity and aid understanding.

Rule 8.2.c.) Assignments shall not be made within an if of else if expression.

Rule 8.2.d.) Any if statement with an else if clause shall end with an else clause. (Note: This is the equivalent of requiring a default in every switch statement, as we do below.)

Example

if (NULL == p_object)
{
    result = ERR_NULL_PTR;
}
else if (p_object = malloc(sizeof(object_t))) // DON'T assign here!
{
    ...
} 
else
{
    // Normal processing steps, 
    // which require many lines of code.
    ...
}

Reasoning

Long clauses can distract the human eye from the decision-path logic. By putting the shorter clause earlier, the decision path becomes easier to follow. (And easier to follow is always good for reducing bugs.) Deeply nested if blocks are a sure sign of a complex and fragile state machine implementation; there is always a safer and more readable way to do the same thing.

Exceptions

For purposes of run-time efficiency, it may sometimes be desirable to reorder the sequence of if-else clauses to ensure the most frequent or most critical case is always found the fastest. Of course, if-else statements are typically not as efficient as tables of function pointers in terms of worst-case analysis.

Enforcement

These rules shall be enforced during code reviews, when reviewers feel it may aid readability.

Comments:

Sometimes a final else statement is indicative of a programming error. I tend to use an assert() to capture the programming error prior to the if-else statement, which makes the final else unnecessary.

Should there be exceptions to the rule for this and for the do-nothing case?

I couldn't agree more than an un-handled final else case is indicative of potential bug. Indeed that's why we have this rule!

I applaud you for checking pre-conditions regularly with assert(). That is a fabulous practice that too few programmers engage in.

My best advice is to move the related assert() into the otherwise-empty else. And if there's nothing to do nor nothing assert there, then that at least merits a comment (explaining why) for the programmers who come along later.

By the way, there are several how-to articles of relevance elsewhere on our website:

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.