Main Content

MISRA C++:2023 Rule 9.3.1

The body of an iteration-statement or a selection-statement shall be a compound-statement

Since R2024b

Description

Rule Definition

The body of an iteration-statement or a selection-statement shall be a compound-statement. 1

Rationale

When used in a subexpression, assignment operators have side effects that are difficult to predict. These side effects might produce results contrary to developer expectations. This rule helps in avoiding confusion between the assignment operator (=) and the equal to operator (==). Do not use the result of an assignment operator.

Polyspace Implementation

Polyspace® reports a violation of this rule if either of these conditions are true:

  • An if statement, else-if statement, or else statement is not followed by a compound statement.

  • A for, switch, while, or do-while statement is not immediately followed by a left brace. For example

    for (i=init_val; i > 0; i--)
       if (arr[i] < 0)
          arr[i] = 0;

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 R2024b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.