A loop steps its counter away from the bound of its condition

tx0/java:wrong-loop-directiondefaultwarningbug

What it finds

for (int i = 0; i < n; i--): a loop whose update moves the counter away from the bound of its condition runs until the counter overflows, or not at all. Usually the comparison or the step was copied from a loop that went the other way.

The condition must compare the counter itself with a bound that does not mention it, the update must be ++, --, or += or -= with a positive integer literal, and the counter must be an int or long that the initializer declares or assigns. Nothing in the loop may assign the counter.

From the rule's source, wrong_loop_direction.rs.

Example from the rule's tests
class Loops {  void f(int[] items, int n, char[] chars) {    for (int i = items.length - 1; i >= 0; i++) {tx0 reports: i++ counts up, but i >= 0 expects i to count down      items[i] = 0;    }    for (int i = 0; i < n; i--) {tx0 reports: i-- counts down, but i < n expects i to count up    }    for (long i = 10; 0 < i; i += 2) {tx0 reports: i += 2 counts up, but 0 < i expects i to count down    }    for (int i = 0; n > i; --i) {tx0 reports: --i counts down    }    int k;    for (k = 0; k < n; k -= 1) {tx0 reports: k -= 1 counts down    }    for (int i = items.length - 1; i >= 0; i--) {    }    for (int i = 0; i < n; i++) {    }    for (int i = 0; i < n; i--) {      i += 2;    }    for (int i = 0; i < items.length; i += n) {    }    for (int i = 0; i < i + n; i--) {    }    for (int i = 0; i < n && items[i] > 0; i--) {    }    for (char c = 'z'; c >= 'a'; c++) {    }    for (int j = 0; k < n; k--) {    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:wrong-loop-direction" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:wrong-loop-direction] reason="..."

tx0 explain tx0/java:wrong-loop-direction shows the same in the terminal. Found a false positive? Report it.