Why is this an issue?
The counter of a for
loop should be updated in the loop’s increment clause. The purpose of a for
loop is to iterate over
a range using a counter variable. It should not be used for other purposes, and alternative loops should be used in those cases.
If the counter is not updated, the loop will be infinite with a constant counter variable. If this is intentional, use a while
or
do
while
loop instead of a for
loop.
If the counter variable is updated within the loop’s body, try to move it to the increment clause. If this is impossible due to certain conditions,
replace the for
loop with a while
or do
while
loop.
How to fix it
Code examples
Noncompliant code example
Move the counter variable update to the loop’s increment clause.
for (int i = 0; i < 10; ) { // Noncompliant, i not updated in increment clause
// ...
i++;
}
int sum = 0
for (int i = 0; i < 10; sum++) { // Noncompliant, i not updated in increment clause
// ...
i++;
}
Compliant solution
for (i = 0; i < 10; i++) { // Compliant
// ...
}
int sum = 0
for (int i = 0; i < 10; i++) { // Compliant
// ...
sum++;
}
Noncompliant code example
If this is impossible and the counter variable must be updated in the loop’s body, use a while
or do
while
loop instead.
for (int sum = 0; sum < 10) { // Noncompliant, sum not updated in increment clause
// ...
if (condition) sum++;
// ...
}
Compliant solution
int sum = 0;
while (sum < 10) { // Compliant
// ...
if (condition) sum++;
// ...
}