Negative index should not be used on arrays

  • ARRAY_INDEX_NEGATIVE
  • Error
  • Medium
  • No tags

This rule applies when a variable with negative value is used as an array index by wrong condition check.

When a variable is checked as negative, using it as an array index is not likely to be a programmer's intent.

Noncompliant Code Example

var arr = [1, 2, 3];
if (x < 0) {
    arr[x] = 3; // ARRAY_INDEX_NEGATIVE alarm: x is negative but is used as array index.
}
if (x <= 0) {
    if (x) arr[x] = 3; // ARRAY_INDEX_NEGATIVE alarm: x is negative but is used as array index.
}

Compliant Code Example

var arr = [1, 2, 3];
if (x >= 0) {
    arr[x] = 3;
}

Version

This rule was introduced in DeepScan 1.0.0-alpha.

See