Main Content

MISRA C++:2008 Rule 6-4-2

All if … else if constructs shall be terminated with an else clause

Description

Rule Definition

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

Rationale

Ending an if... else if construct 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;  
    } 

    return result;
}

Because no else if statement exists in this if construct, no final else statement is required within the construct.

#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 R2013b