Our organization has a required coding rule (without any explanation) that:
if … else if constructs should be terminated with an el
Your company followed MISRA coding guidance. There are a few versions of these guidelines that contain this rule, but from MISRA-C:2004†:
Rule 14.10 (required): All if … else if constructs shall be terminated with an else clause.
This rule applies whenever an if statement is followed by one or more else if statements; the final else
ifshall be followed by anelsestatement. In the case of a simpleifstatement then theelsestatement need not be included. The requirement for a finalelsestatement is defensive programming. Theelsestatement shall either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a finaldefaultclause in aswitchstatement. For example this code is a simple if statement:if ( x < 0 ) { log_error(3); x = 0; } /* else not needed */whereas the following code demonstrates an
if,else ifconstructif ( x < 0 ) { log_error(3); 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 */ }
In MISRA-C:2012, which supersedes the 2004 version and is the current recommendation for new projects, the same rule exists but is numbered 15.7.
Example 1: in a single if statement programmer may need to check n number of conditions and performs single operation.
if(condition_1 || condition_2 || ... condition_n)
{
//operation_1
}
In a regular usage performing a operation is not needed all the time when if is used.
Example 2:
Here programmer checks n number of conditions and performing multiple operations. In regular usage if..else if is like switch you may need to perform a operation like default. So usage else is needed as per misra standard
if(condition_1 || condition_2 || ... condition_n)
{
//operation_1
}
else if(condition_1 || condition_2 || ... condition_n)
{
//operation_2
}
....
else
{
//default cause
}
† Current and past versions of these publications are available for purchase via the MISRA webstore (via).