C#

C#

Made by DeepSource

Incorrect variable being modified in nested loops CS-W1074

Bug risk
Critical

A for loop has 3 basic elements:

  1. Initial assignment,
  2. Condition, and,
  3. Incrementors and/or decrementors.

In this case, the inner for loop is modifying a variable that belongs to the outer/enclosing for loop. This can result in an undefined behavior such as infinite loop. It is therefore recommended that you modify the right variable to ensure that your loop terminates as required.

Bad Practice

for (var i = 0; i < ub; i++)
{
    // `i` is incremented instead of `j`
    for (var j = 0; j < ub; i++)
    {
    }
}

Recommended

for (var i = 0; i < ub; i++)
{
    // `j` is now correctly incremented instead of `i`.
    for (var j = 0; j < ub; j++)
    {
    }
}