Rule Definition
When an if statement is followed by one or more else if statements then the final else if, shall be followed by an else statement. In the case of a simple if statement the else statement need not be included. The final else statement, which should either take appropriate action or contain a suitable comment as to why no action is taken, is defensive programming.
Remediation
Ensure logical completeness by using else block at the end of "if...else if" contruct
Violation Code Sample
if ( x < 0 )
{
log_error ( 3 );
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
}
Fixed Code Sample
if ( x < 0 )
{
log_error ( 3 );
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else // this else clause is required, even if the
{ // developer expects this will never be reached
// No change in value of x
}
Reference
Standards Reference:
MISRA C++ 2008, Rule 6–4–2: All if … else if constructs shall be terminated with an else clause.
Related Technologies
Technical Criterion
Programming Practices - Structuredness
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.