If a for
or while
statement uses a loop counter, than it is safer to use an inequality operator a relational operator (such as <
) to terminate the loop than using an equality operator.inequality operator (operator !=
).
Anchor |
---|
| nce_inequality_multistep |
---|
| nce_inequality_multistep |
---|
|
Noncompliant Code Example (inequality)
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
Code Block |
---|
|
int i;
for (i = 1; i != 10; i += 2 ) {
/* ... */
}
|
Anchor |
---|
| cs_relational_multistep |
---|
| cs_relational_multistep |
---|
|
Compliant Solution
...
(relational operator)
Using the relational operator <=
instead of an inequality An inequality comparison guarantees loop termination.
Code Block |
---|
|
int i;
for (i = 1; i <= 10; i += 2 ) {
/* ... */
}
|
Anchor |
---|
| nce_inequality |
---|
| nce_inequality |
---|
|
Noncompliant Code Example (inequality)
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.
Code Block |
---|
|
void f(int begin, int end) {
int i;
for (i = begin; i != end; ++i) {
/* ... */
}
}
|
Anchor |
---|
| cs_relational |
---|
| cs_relational |
---|
|
Compliant Solution (relational operator)
Again, an inequality comparison using a relational operator instead of inequality guarantees loop termination. If begin >= end
the loop never executes its body.
Code Block |
---|
|
void f(int begin, int end) {
int i;
for (i = begin; i << end; ++i) {
/* ... */
}
}
|
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.
Code Block |
---|
|
int i;
for (i = 1; i == 5; i++i) {
/* ... */
}
|
Risk Assessment
...