Main Content

MISRA C++:2008 Rule 6-5-4

The loop-counter shall be modified by one of: --, ++, -=n, or +=n ; where n remains constant for the duration of the loop

Description

Rule Definition

The loop-counter shall be modified by one of: --, ++, -=n, or +=n ; where n remains constant for the duration of the loop.

Rationale

If the loop-counter modifier of the loop is not constant, the loop might end unpredictably, causing results contrary to your expectations. Constant increments create predictable loop termination.

Polyspace Implementation

Polyspace® reports this defect whenever the modifier of a loop-counter is not constant. Polyspace also reports this defect when you modify a loop by -=n or +=n and modify n within the loop.

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

Because the first for loop uses the loop-counter modifier of +=x and modifies the variable x within the for loop, Polyspace flags the for loop as noncompliant.

The second for loop shows a compliant case of using a loop-counter modifier of +=y, where y is not modified within the loop.

The third for loop modifies the loop counter by using the return value of a function, ex2(). Because the function returns a different value in each iteration, the loop-counter modifier is not constant. Polyspace flags the for loop as noncompliant.

#include <cstdint>

int i, x = 0;
int y, z = 1;

int ex2()
{
    return z;
}

void example()
{
    for (i = 0; i <= 10; i += x) {          //Noncompliant
        x += 1;
    }

    for (i = 0; i <= 10; i += y) {          //Compliant
        z += i;
    }

    for (i = 0; i >= 10; i -= ex2()) {      //Noncompliant
        z += i;
    }

}

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b