MISRA C:2012 Rule 14.2
A for loop shall be well-formed
Description
Rule Definition
A for loop shall be well-formed1 .
Rationale
The for
loop provides a flexible looping facility. You can perform other
operations besides the loop counter initialization, termination, and increment in
the control statement, and increment the loop counter anywhere inside the loop body.
However, using a restricted loop format makes your code easier to review and to
analyze.
Polyspace Implementation
A for
loop consists of three expressions, a loop counter, a
loop flag and a loop body. The last assigned variable of the first expression is
considered the loop counter. The checker raises a violation if the components of the
for
loop shows these properties:
First expression of the for loop —
Does not initialize the loop counter.
Has a side effect other than setting the value of loop counter.
The second expression of the for loop —
Does not contains a comparison operation involving the loop counter.
Uses an object that is also used in the loop body.
Has a side effect.
The third expression of the for loop —
Contains an operation other than incrementing or decrementing the loop counter (separated by a comma from the increment or decrement).
Uses an object that is also used in the loop body.
Has a side effect other than updating the loop counter.
The loop counter —
Has a data type that is not an integer or a pointer type.
Is modified inside the loop body.
Polyspace® does not raise a violation when the second expression includes a binary operation that involves the loop counter. Loops that uses more than one loop counter are reported as violations of the rule. If the loop counter is in a structure or class, updating the structure or class is considered updating the loop counter.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Control Statement Expressions |
Category: Required |
AGC Category: Readability |
Version History
See Also
MISRA C:2012 Rule 14.1
| MISRA C:2012 Rule 14.3
| MISRA C:2012 Rule 14.4
| Check MISRA C:2012 (-misra3)
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.