for_loop_updates_wrong_variable
Reports a for loop whose update changes none of the variables its condition tests. Update the variable the condition tests, or test the one the update changes.
- Tier
- blocking
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- none
What it reports
Section titled “What it reports”A for loop whose update changes none of the variables its condition tests: for (var i = 0; i < n; j++). Nothing else in the loop changes them either, so the condition gives the same answer on every pass, and a loop that starts never ends. The violation is on the update.
It reports a loop only where that is certain:
- The condition is made of local variables and parameters, literals, constants, final fields, the core library’s operators and its read-only members such as
length. It tests at least one local variable or parameter. - Every update assigns, increments or decrements a local variable or a parameter, and none of them is one the condition tests.
- Neither the body, nor the update, nor a closure anywhere in the function writes a tested variable.
- A tested variable that holds an object that can change, such as a list whose
lengththe condition reads, is not mentioned in the body or the update at all. - The body holds no
break,continue,return,throw,rethroworyield.
The loop hangs the isolate or, with an index in the body, runs past the end of a list and throws. The usual slip is a copied loop whose variable was renamed in two places of three.
Example
Section titled “Example”for (var row = 0; row < rows.length; row++) { for (var column = 0; column < columns; row++) { paint(row, column); }}for (var row = 0; row < rows.length; row++) { for (var column = 0; column < columns; column++) { paint(row, column); }}Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression, which goes above the line of the update:
// This loop waits for the isolate to be killed.// ignore: for_loop_updates_wrong_variablefor (var i = 0; i < n; tick++) {// ignore_for_file: assay/for_loop_updates_wrong_variable silences it in a whole file, and // ignore: assay/for_loop_updates_wrong_variable with the prefix works too. See Suppressions.