...
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (
...
Equality Operators)
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
...
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (
...
Relational Operator)
Using the relational operator <=
instead of an equivalence equality operator guarantees loop termination.
...
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (
...
Equality Operators)
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.
...
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (
...
Relational Operator)
Again, using a relational operator instead of equivalence guarantees loop termination. If begin >= end
the loop never executes its body.
...
Anchor | ||||
---|---|---|---|---|
|
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
:
...
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (
...
Boundary Conditions)
A compliant solution is to compare against the difference between the maximum representable value of a type and the increment.
...