The index variable of for statement should be initialized and updated properly

  • BAD_FOR_STATEMENT
  • Error
  • Medium
  • No tags

This rule applies when a for statement has an improper initialization or update of the index variable.

for statement may behave unintendedly in the following cases:

  1. The index variable is initialized by the final value of the loop
  2. An irrelevant variable is updated instead of the index variable
  3. The direction of the index update is inconsistent with the loop termination condition

Noncompliant Code Example

View with compliant examples side by side
// Example 1
for (let i = arraySize; i < arraySize; i++) { // BAD_FOR_STATEMENT alarm because index 'i' is initialized by the final value of the loop.
}

// Example 2
for (let i = 0; i < array.length; index++) { // BAD_FOR_STATEMENT alarm because irrelevant variable 'index' is updated.
}

// Example 3
for (let i = 0; i < array.length; i--) { // BAD_FOR_STATEMENT alarm because index 'i' is updated in wrong direction.
}

Compliant Code Example

View with noncompliant examples side by side
for (let i = 0; i < array.length; i++) {
}

Version

This rule was introduced in DeepScan 1.19.0.

See