This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 9.4.1 - All if ... else if constructs shall be terminated with an else statement
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
A final else shall always be provided whenever an if statement is followed by a sequence of one or more else
if constructs.
Note: a final else statement is not required for a simple if statement.
Rationale
Terminating a sequence of if ... else if constructs with an else statement is defensive programming, complementing the
requirement for a default clause in a switch statement (see M23_113: MISRA C++ 2023 Rule 9.4.2).
The addition of an else statement, even when empty, indicates that consideration has been given regarding the behaviour when all other
conditions evaluate to false.
Example
void f1( bool flag_1, bool flag_2 )
{
if ( flag_1 )
{
action_1();
}
else if ( flag_2 )
{
action_2();
} // Non-compliant
}
void f2(bool flag_1, bool flag_2)
{
if ( flag_1 )
{
action_1();
}
else if ( flag_2 )
{
action_2();
}
else // Compliant
{
}
}
void f3( bool flag )
{
if ( flag )
{
action_1();
} // Simple 'if' - rule does not apply
}
Copyright The MISRA Consortium Limited © 2023