If a while or for statement uses a loop counter, and increments or decrements it by more than one, it should use an inequality operator to terminate the loop.
Noncompliant Code Example
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
for ( i = 1; i != 10; i += 2 ) { // ... }
Compliant Solution
An inequality comparison guarantees loop termination.
for ( i = 1; i <= 10; i += 2 ) { // ... }
Risk Assessment
Testing for exact values runs the risk of a loop terminating much longer than expected, or never terminating at all.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC36-J |
low |
unlikely |
low |
P1 |
L3 |
Automated Detection
None.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as MSC21-C. Use inequality to terminate a loop whose counter changes by more than one .
This rule appears in the C++ Secure Coding Standard as MSC21-CPP. Use inequality to terminate a loop whose counter changes by more than one.
References
[[MISRA 04]]