Main Content

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.

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

expand all

#include <cstdint>

int32_t ctr, level = 1;
bool fuelTankNotEmpty = true;

void example()
{
	for(ctr = 0 ; ctr <= 10 && level >= 0; ctr++)		//Noncompliant
	{
		level--;
	}
	
	for (ctr = 0; ctr <= 10 && fuelTankNotEmpty; ctr++)	//Compliant
	{
		level--;
		fuelTankNotEmpty = (level >= 0);
	}

}

In the first for loop, because level is not a Boolean and is modified within the statement, Polyspace flags it as noncompliant.

The second loop shows how to use a Boolean flag to be compliant with this rule.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b