Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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.

Code Block
bgColor#FFCCCC
for ( i = 1; i != 10; i += 2 ) {
  // ...
}

Compliant Solution

An inequality comparison guarantees loop termination.

Code Block
bgColor#ccccff
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

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

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

Wiki Markup
\[[MISRA 04|AA. C References#MISRA 04]\]

...