All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2251.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

A for loop with a counter that moves in the wrong direction, away from the stop condition, is not an infinite loop. Because of wraparound, the loop will eventually reach its stop condition, but in doing so, it will probably run more times than anticipated, potentially causing unexpected behavior.

How to fix it

If your stop condition indicates a maximum value, the iterator should increase towards it. Conversely, if your stop condition indicates a minimum value, the iterator should decrease towards it.

Code examples

Noncompliant code example

for (int i = 0; i < maximum; i--)  // Noncompliant: runs until it underflows to int.MaxValue
{
    // ...
}

for (int i = maximum; i >= maximum; i++)  // Noncompliant: runs until it overflows to int.MinValue
{
    // ...
}

Compliant solution

for (int i = 0; i < maximum; i++) // Compliant: Increment towards the maximum value
{
}

for (int i = maximum; i >= 0; i--) // Compliant: Decrement towards the minimum value
{
    // ...
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy