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 Codeflag = 1;
for ( i = 0; (i < 5) && (flag == 1); i++ ) {
/* ... */
i = i + 3; /* loop counter updated */
}
flag = 1;
for ( i = 0; (i < 5) && (flag == 1); i++ ) {
/* ... */
flag = 0; /* not the loop counter */
}
References
http://caxapa.ru/thumbs/468328/misra-c-2004.pdf https://rules.sonarsource.com/java/RSPEC-127About 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.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_loopcountermodification-avoid-loop-counter-modification/
https://doc.casthighlight.com/alt_loopcountermodification-avoid-loop-counter-modification/
Comments