org.sonar.plugins.csharp.S1994.html Maven / Gradle / Ivy
Why is this an issue?
The for
loop is designed to iterate over a range using a counter variable, with the counter being updated in the loop’s increment
section. Misusing this structure can lead to issues such as infinite loops if the counter is not updated correctly. If this is intentional, use a
while
or do while
loop instead of a for
loop.
Using a for loop for purposes other than its intended use can lead to confusion and potential bugs. If the for
loop structure does not
fit your needs, consider using an alternative iteration statement.
How to fix it
Move the counter variable update to the loop’s increment section. If this is impossible, consider using another iteration statement instead.
Code examples
Noncompliant code example
int sum = 0;
for (int i = 0; i < 10; sum++) // Noncompliant: `i` is not updated in the increment section
{
// ...
i++;
}
for (int i = 0;; i++) // Noncompliant: the loop condition is empty although incrementing `i`
{
// ...
}
Compliant solution
int sum = 0;
for (int i = 0; i < 10; i++)
{
// ...
sum++;
}
int i = 0;
while (true)
{
// ...
i++;
}
Resources
Documentation
- Microsoft Learn - The
for
statement
- Microsoft Learn - Iteration
statements -
for
, foreach
, do
, and while
© 2015 - 2024 Weber Informatics LLC | Privacy Policy