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.
Move the counter variable update to the loop’s increment section. If this is impossible, consider using another iteration statement instead.
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`
{
// ...
}
int sum = 0;
for (int i = 0; i < 10; i++)
{
// ...
sum++;
}
int i = 0;
while (true)
{
// ...
i++;
}
for
statement for, foreach, do, and while