A for loop termination condition should test the loop counter against an invariant value that does not change during the execution of
the loop. Invariant termination conditions make the program logic easier to understand and maintain.
This rule tracks three types of non-invariant termination conditions:
for loop Make the termination condition invariant by using a constant or a local variable instead of an expression that could change during the execution of the loop.
for (int i = 0; i < foo(); i++) { // Noncompliant, "foo()" is not an invariant
// ...
}
int end = foo();
for (int i = 0; i < end; i++) { // Compliant, "end" does not change during loop execution
// ...
}
If this is impossible and the counter variable must be updated in the loop’s body, use a while or do while
loop instead of a for loop.
for (int i = 0; i < 10; i++) {
// ...
if (condition) i++; // Noncompliant, i is updated from within body
// ...
}
int i = 0;
while (i++ < 10) { // Compliant
// ...
if (condition) sum++;
// ...
}