AUTOSAR C++14 Rule M6-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.
Rationale
Loops terminate when the loop-counter value satisfies a specified termination condition. You can use additional loop-control variables to end a loop early if needed.
For instance:
for(ctr = 0 ; ctr <= 10; ctr++) {…}terminates when the value ofctris greater than10.for(ctr = 0 ; ctr <= 10 && level > 0; ctr++) {…}terminates when the value ofctris greater than10or when the value oflevelis greater than0.
In the second example, the condition level > 0 might not convey the reason for early loop termination. By using a Boolean variable as a loop-control variable, you can provide 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 often referred to as 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, Automated |