MISRA C++:2023 Rule 9.5.1
Description
Rule Definition
Legacy for
statements should be simple.
Rationale
Legacy for
statements can introduce side effects that can result
in confusion and unexpected results if not accounted for. It is important to review
legacy iteration statements and handle all side effects properly. Due to the complexity
of this type of review, using the Standard Library algorithms is preferable to using
legacy iteration statements. If using a simple for
statement, make
certain the loop progresses and terminates.
Consider a general legacy for
statement:
for(init-statement; condition; increment-statement;) { //... }
A legacy for
statement is simple if it meets these criteria, as
stated in the MISRA™ C++:2023 standard.
only declares and initializes a loop counter of integer type.init-statement
uses one of the relational operatorscondition
<
,>
,<=
, and>=
to compare the loop counter to the loop bound.You only modify the loop counter by incrementing or decrementing by a loop step within
.increment-statement
The type of the loop bound and loop counter are the same, or if the loop bound is a constant expression, the type of the loop counter has a large enough range to accommodate the value of the loop bound.
The loop bound and loop step are constant expressions or variables that are not modified within the
for
statement.The loop counter, loop bound, and loop step are neither bound to non-
const
references nor are their addresses assigned to pointers to non-const
values. This ensures that the loop counter, loop bound, and loop step remain unchanged throughout the loop execution.
Use the C++ Standard Library algorithms in place of legacy for
statements wherever possible. Use a range-for
statement instead of a
legacy for
statement when iterating over the contents of a
container.
This rule does not apply to while
and do-while
loops.
Polyspace Implementation
Polyspace® reports a rule violation whenever a legacy for
statement that is not simple is used in code. Polyspace uses the definition of simple as detailed in the
MISRA™ C++:2023 specifications.
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
Check Information
Group: Statements |
Category: Advisory |
Version History
Introduced in R2024b