MISRA C++:2008 Rule 6-5-6
A loop-control-variable other than the loop-counter which is modified in statement shall have type bool
Description
Rule Definition
A loop-control-variable other than the loop-counter which is modified in statement shall have type bool.1
Rationale
Loops terminate when the loop-counter value meets a termination condition. You can use additional loop-control-variables if you want to end a loop early.
For instance:
for(ctr = 0 ; ctr <= 10; ctr++) {…} terminates when the value of
ctr is greater than 10.
for(ctr = 0 ; ctr <= 10 && level > 0; ctr++) {…}
terminates when the value of ctr is greater than 10 or
when the value of level is greater than 0.
In the second instance, it is not clear why the condition level >= 0
terminates the loop early. By using a Boolean variable as a loop-control-variable for early
termination, you can use a more descriptive name that reflects the early termination state.
For example:
for(ctr = 0 ; ctr <= 10 && fuelTankNotEmpty; ctr++)
{
/...
fuelTankNotEmpty = (level >= 0);
}
This Boolean variable is called a flag. Boolean flags make loop control logic easier to understand.
Polyspace Implementation
Polyspace® raises this defect whenever a non-Boolean loop-control-variable is modified within the loop statement.
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: Required |
Version History
Introduced in R2013b
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.