Skip to content

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

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 length the condition reads, is not mentioned in the body or the update at all.
  • The body holds no break, continue, return, throw, rethrow or yield.

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.

Violating
for (var row = 0; row < rows.length; row++) {
for (var column = 0; column < columns; row++) {
paint(row, column);
}
}
Corrected
for (var row = 0; row < rows.length; row++) {
for (var column = 0; column < columns; column++) {
paint(row, column);
}
}

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.

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_variable
for (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.