V3218. Cycle condition may be incorrect due to an off-by-one error.
The analyzer has detected that an incorrect maximum or minimum value of the collection index is used in the loop. The index is greater or lesser than the intended value by one. This is usually due to an error in the loop condition.
Take a look at an example with the for
loop:
void PrintArray(int[] numbers)
{
for (int i = 0; i <= numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
The i <= numbers.Length
loop condition includes the index range from 0
to numbers.Length
. The first index is 0
, and the index of the last element is numbers.Length - 1
. As a result, numbers.Length
exceeds the last valid index by one, leading to an off-by-one error.
The fixed code looks like this:
void PrintArray(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
Let's look at an example of iterating over the array in reverse order:
void PrintArray(int[] numbers)
{
for (int i = numbers.Length - 1; i > 0; i--)
{
Console.WriteLine(numbers[i]);
}
}
Since the i > 0
condition restricts the index to 1
, the first array element is not printed to the console.
In this case, the fixed code looks like this:
void PrintArray(int[] numbers)
{
for (int i = numbers.Length - 1; i >= 0; i--)
{
Console.WriteLine(numbers[i]);
}
}
Now the loop condition is correct, and all array elements will be printed to the console.
The diagnostic rule also covers the while
and do while
loops.
Take a look at an example with the while
loop:
void PrintArray(List<int> numbersList)
{
int i = 0;
while (i <= numbersList.Count)
{
Console.WriteLine(numbersList[i]);
i++;
}
}
The loop condition includes an index value equal to the collection size, which results in a collection overrun.
The fixed code:
void PrintArray(List<int> numbersList)
{
int i = 0;
while (i < numbersList.Count)
{
Console.WriteLine(numbersList[i]);
i++;
}
}
After the fix, the collection will be fully iterated, and no exception will occur.