MISRA C++:2023 Rule 9.5.1
Description
Rule Definition
Legacy for statements should be simple. 1
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-statementuses 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-statementThe 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
forstatement.The loop counter, loop bound, and loop step are neither bound to non-
constreferences nor are their addresses assigned to pointers to non-constvalues. 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
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.