A loop body always ends in a jump out of the loop, so it runs at most once
What it finds
A for, while or do loop whose body ends in break, return or throw, with no continue that could start another pass, runs its body at most once. Either the jump was meant to be conditional, or the loop is an if in disguise. foreach is left alone, as returning from its first pass is a common way to take the first element of a sequence, and so is do { ... } while (false), a block that break can leave. For the same reason while (true) and while loops whose condition fetches the next item, as reader.Read(), MoveNext() or a Try method with an out argument, are left alone.
From the rule's source, loop_runs_once.rs.
using System.Collections.Generic; class Scanner{ int First(int[] items) { for (int i = 0; i < items.Length; i++)tx0 reports: this loop ends every pass with return, so it runs at most once { if (items[i] > 0) { items[i] = 0; } return items[i]; } return -1; } void Drain(Queue<int> queue) { while (queue.Count > 0)tx0 reports: this loop ends every pass with break, so it runs at most once { queue.Dequeue(); break; } } int Retry(Queue<int> queue) { while (queue.Count > 0) { int next = queue.Dequeue(); if (next < 0) { continue; } return next; } for (int i = 0; i < 3; i++) { if (i == 2) { break; } } do { if (queue.Count == 0) { break; } queue.Dequeue(); break; } while (false); foreach (int item in queue) { return item; } while (queue.Count > 0)tx0 reports: this loop ends every pass with return, so it runs at most once { for (int j = 0; j < 2; j++) { continue; } return 1; } return 0; }} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp: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/csharp:loop-runs-once] reason="..."tx0 explain tx0/csharp:loop-runs-once shows the same in the terminal. Found a false positive? Report it.