The body of a for or while loop always leaves the loop at its end, so it runs at most once

tx0/c:loop-runs-oncerecommendedwarningreliability/control-flowdepth fastbug

What it finds

for (i = 0; i < n; i++) { if (ok(i)) found = i; break; }: the body ends with an unconditional break, return or goto and has no continue, so the loop never reaches its second pass, and the update and the condition run once at most. Often the break belongs inside the if above it.

The jump must come right after an if without braces or else, where it looks as if it belonged to the if; loops without a condition, which are left this way on purpose, are left alone.

From the rule's source, loop_runs_once.rs.

Example from the rule's tests
int first_match(const int *items, int n, int wanted){  int found = -1;  for (int i = 0; i < n; i++) {    if (items[i] == wanted)      found = i;    break;tx0 reports: this break ends every pass, so the loop runs at most once  }  for (int i = 0; i < n; i++) {    if (items[i] != wanted)      continue;    found = i;    break;  }  return found;}
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 from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/c:loop-runs-once" = "warning"

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/c:loop-runs-once] reason="..."

tx0 explain tx0/c:loop-runs-once shows the same in the terminal. Found a false positive? Report it.