A for loop with a counter moving away from the end of the specified range is likely a programming mistake.
If the intention is to iterate over the specified range, this differs from what the loop does because the counter moves in the wrong direction.
If the intention is to have an infinite loop or a loop terminated only by a break statement, there are two problems:
break statement should be implemented using a while or do
while loop to make the developer’s intention clear to the reader. Change the direction of the counter.
for (int i = 10; i > 0; i++) { // Noncompliant, wrong direction
System.out.println("Hello, world!") // executed ca. 2 billion times
}
public void doSomething(String [] strings) {
for (int i = 0; i < strings.length; i--) { // Noncompliant, wrong direction
String string = strings[i]; // ArrayIndexOutOfBoundsException when i reaches -1
// ...
}
}
for (int i = 10; i > 0; i--) { // Compliant
System.out.println("Hello, world!") // executed 10 times
}
public void doSomething(String [] strings) {
for (int i = 0; i < strings.length; i++) { // Compliant
String string = strings[i];
// ...
}
}
If the intention is to have an infinite loop or a loop terminated only by a break statement, use a while or a do
while statement instead.
for (int i = 0; i < 0; i++) { // Noncompliant, loop is not infinite
String event = waitForNextEvent();
if (event == "terminate") break;
processEvent(event);
}
while (true) { // Compliant
String event = waitForNextEvent();
if (event == "terminate") break;
processEvent(event);
}