If a for
or while
statement uses a loop counter, than it is safer to use a relational operator (such as <
) to terminate the loop than using an inequality operator (operator !=
).
Noncompliant Code Example (equivalence)
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
int i; for (i = 1; i != 10; i += 2) { /* ... */ }
Compliant Solution (relational operator)
Using the relational operator <=
instead of an equivalence guarantees loop termination.
int i; for (i = 1; i <= 10; i += 2 ) { /* ... */ }
Noncompliant Code Example (equivalence)
It is also important to ensure termination of loops where the start and end values are variables that might not be properly ordered. The following function assumes that begin < end
; if this is not the case, the loop will never terminate.
void f(int begin, int end) { int i; for (i = begin; i != end; ++i) { /* ... */ } }
Compliant Solution (relational operator)
Again, using a relational operator instead of equivalence guarantees loop termination. If begin >= end
the loop never executes its body.
void f(int begin, int end) { int i; for (i = begin; i < end; ++i) { /* ... */ } }
Noncompliant Code Example (boundary conditions)
Numerical comparison operators do not always ensure loop termination when comparing against the minimum or maximum representable value of a type, such as INT_MIN
or INT_MAX
:
void f(int begin, int step) { int i; for (i = begin; i <= INT_MAX; i += step) { /* ... */ } }
Compliant Solution (boundary conditions)
A compliant solution is to compare against the difference between the minimum or maximum representable value of a type and the increment.
void f(int begin, int step) { if (0 < step) { int i; for (i = begin; i <= INT_MAX - step; i += step) { /* ... */ } } }
Exceptions
MSC21-EX1: If the counter for a loop is 1, and it is known that the starting value of a loop is less than or equal to the ending value, then the equals operator may be used to terminate the loop. Likewise, if the loop counter is -1, and it is known that the starting value of the loop is greater than, or equal to the ending value, then the equals operator may be used to terminate the loop.
int i; for (i = 1; i == 5; ++i) { /* ... */ }
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 |
---|---|---|---|---|---|
MSC21-C |
low |
unlikely |
low |
P1 |
L3 |
Automated Detection
ROSE can detect violations of this rule.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
- MSC21-CPP. Use inequality to terminate a loop whose counter changes by more than one
- MSC15-J. Use numerical comparison operators to terminate a loop whose counter changes by more than one
References
[[MISRA 04]]