Avoid loop counter modification

Why you should care

Loop counters shall not be modified in the body of the loop. However other loop control variables representing logical values may be modified in the loop, for example a flag to indicate that something has been completed, which is then tested in the for statement.

How we detect

CAST Highlight counts one occurrence each time a “for” loop has its loop counter modified inside its body.

Bad Code

flag = 1;
for ( i = 0; (i < 5) && (flag == 1); i++ ) {
/* ... */
i = i + 3; /* loop counter updated */
}

Good Code

flag = 1;
for ( i = 0; (i < 5) && (flag == 1); i++ ) {
/* ... */
flag = 0; /* not the loop counter */
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.