Rules:
8.2.a. It is a preferred practice that the shortest (measured in lines of code) of the if and else if clauses should be placed first.
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.
8.2.c. Assignments shall not be made within an if or else if test.
8.2.d. Any if statement with an else if clause shall end with an else clause.13
Example:
if (NULL == p_object)
{
result = ERR_NULL_PTR;
}
else if (p_object = malloc(sizeof(object_t))) // No assignments!
{
...
}
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…else statements 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.
Enforcement: These rules shall be enforced during code reviews.
Footnotes
[13] This is the equivalent of requiring a default case in every switch statement.