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.3.1 - The body of an iteration-statement or a selection-statement shall be a compound-statement
[Koenig] 24
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
The body of an iteration-statement (while, do ... while, for) or a selection-statement
(if, else, switch) shall be a compound-statement.
Rationale
It is possible for a developer to mistakenly believe that a sequence of statements forms the body of an iteration-statement or
selection-statement by virtue of their indentation. The accidental inclusion of a semi-colon after the controlling expression is a particular
danger, leading to a null control statement. Using a compound-statement clearly defines which statements actually form the body.
Additionally, it is possible that indentation may lead a developer to associate an else statement with the wrong if.
Exception
An if statement that is the statement to an else need not be contained within a compound-statement.
Example
The layout for the compound-statement and its enclosing braces are style issues which are not addressed by this document; the style used
in the following examples is not mandatory.
Maintenance to the following
while ( data_available )
process_data(); // Non-compliant
could accidentally give
while ( data_available )
process_data(); // Non-compliant
service_watchdog();
where service_watchdog should have been added to the loop body. The use of a compound-statement significantly reduces the
chance of this happening.
The next example appears to show that action_2 is the else statement to the first if.
if ( flag_1 )
if ( flag_2 ) // Non-compliant
action_1(); // Non-compliant
else
action_2(); // Non-compliant
when the actual behaviour is
if ( flag_1 )
{
if ( flag_2 )
{
action_1();
}
else
{
action_2();
}
}
The use of _compound-statement_s ensures that if and else associations are clearly defined.
The exception allows the use of else if, as shown below
if ( flag_1 )
{
action_1();
}
else if ( flag_2 ) // Compliant by exception
{
action_2();
}
else { } // Compliant - else with empty block
The following example shows how a spurious semi-colon could lead to an error
while ( flag ); // Non-compliant
{
flag = fn();
}
while ( !data_available ) { } // Compliant - loop with empty body
Copyright The MISRA Consortium Limited © 2023