cmisrasafety-critical

What is the benefit of terminating if … else if constructs with an else clause?


Our organization has a required coding rule (without any explanation) that:

if … else if constructs should be terminated with an else clause

Example 1:

if ( x < 0 )
{
   x = 0;
} /* else not needed */

Example 2:

if ( x < 0 )
{
    x = 0;
}
else if ( y < 0 )
{
    x = 3;
}
else    /* this else clause is required, even if the */
{       /* programmer expects this will never be reached */
        /* no change in value of x */
}

What edge case is this designed to handle?

What also concerns me about the reason is that Example 1 does not need an else but Example 2 does. If the reason is re-usability and extensibility, I think else should be used in both cases.


Solution

  • As mentioned in another answer, this is from the MISRA-C coding guidelines. The purpose is defensive programming, a concept which is often used in mission-critical programming.

    That is, every if - else if must end with an else, and every switch must end with a default.

    There are two reasons for this:


    EDIT

    Regarding why else is not needed after every single if:

    An if-else or if-else if-else completely covers all possible values that a variable can have. But a plain if statement is not necessarily there to cover all possible values, it has a much broader usage. Most often you just wish to check a certain condition and if it is not met, then do nothing. Then it is simply not meaningful to write defensive programming to cover the else case.

    Plus it would clutter up the code completely if you wrote an empty else after each and every if.

    MISRA-C:2012 15.7 gives no rationale why else is not needed, it just states:

    Note: a final else statement is not required for a simple if statement.