Main Content

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

An if ( condition ) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement

Description

Rule Definition

An if ( condition ) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement.

Rationale

If you use single statements as bodies of if or if...else constructs, then attempting to change the body into a compound statement might result in logic errors and unexpected results. This rule ensures that braces are not missed or forgotten when attempting to turn a single statement body into a compound statement body. Failure to use compound statements might provide unexpected results and cause developer confusion. Use { } braces to create compound statements. Use braces even when the if statement is simple and contains only a single statement.

Polyspace Implementation

Polyspace® raises this defect whenever a compound statement does not immediately follow an if statement, else-if statement, or 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;   //Compliant
    } 
    else if (test <= 5) 
    {
        result = test - result;   //Compliant
    } 
    else                          //Noncompliant
        result = test;

    return result;
}

Because the else statement does not use { } braces to form a compound statement, Polyspace flags it as noncompliant.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b