Negative index should not be used on arrays

  • ARRAY_INDEX_NEGATIVE
  • Error
  • Medium
  • cwe

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

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

Compliant Code Example

View with noncompliant examples side by side
var arr = [1, 2, 3];
if (x > 0) {
    arr[x] = 3;
}

Version

This rule was introduced in DeepScan 1.0.0-alpha.

See

Was this documentation helpful?