Main Content

MISRA C++:2023 Rule 9.4.1

All if ... else if constructs shall be terminated with an else statement

Since R2024b

Description

Rule Definition

All if ... else if constructs shall be terminated with an else statement.

Rationale

Ending an if... else if statement with an else statement is defensive programming. This final else statement acts as a fail-safe in case a unique situation occurs where the code progresses past the if and else if statements.

When an if statement is followed by one or more else if statements, follow the final else if statement with an else statement. Within the else statement provide an action. If no action is needed, provide a comment as to why no action is taken.

Polyspace Implementation

Polyspace® raises this defect whenever an if … else if construct does not end with an else statement.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>

int example(int test, int result)
{
    if (test > 5) 
    {
        test--;
        result = test + result;  
    } 
    else if (test <= 5) 			//Noncompliant		
    {
        result = test - result;   
    } 

    return result;
}

Because the final else if statement is not followed by a closing else statement, Polyspace marks it as noncompliant. Even though there should be no situation where a value of test progresses past both the if and else if statements, the additional else statement is required.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b