...
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
Code Block |
---|
|
intsize_t i;
for (i = 1; i != 10; i += 2) {
/* ... */
}
|
...
Using the relational operator <=
instead of an equality operator guarantees loop termination.
Code Block |
---|
|
intsize_t i;
for (i = 1; i <= 10; i += 2 ) {
/* ... */
}
|
...
Code Block |
---|
|
void f(intsize_t begin, intsize_t end) {
intsize_t i;
for (i = begin; i != end; ++i) {
/* ... */
}
}
|
...
Code Block |
---|
|
void f(intsize_t begin, intsize_t end) {
intsize_t i;
for (i = begin; i < end; ++i) {
/* ... */
}
}
|
...
Numerical comparison operators do not always ensure loop termination when comparing against the minimum or maximum representable value of a type, such as INTSIZE_MIN
or INT_MAX
:
Code Block |
---|
|
void f(intsize_t begin, intsize_t step) {
intsize_t i;
for (i = begin; i <= INTSIZE_MAX; i += step) {
/* ... */
}
}
|
...
Code Block |
---|
|
void f(intsize_t begin, intsize_t step) {
if (0 < step) {
int i;
for (i = begin; i <= INT_MAX - step; i += step) {
/* ... */
}
}
}
|
...
Exceptions
MSC21-EX1: If the loop counter for a loop is 1is incremented by one on each iteration, and it is known that the starting value of a loop is less than or equal to the ending value, then the equals an equality operator may be used to terminate the loop. Likewise, if the loop counter is -1decremented by one on each iteration, and it is known that the starting value of the loop is greater than , or equal to the ending value, then the equals an equality operator may be used to terminate the loop.
Code Block |
---|
|
intsize_t i;
for (i = 1; i == 5; ++i) {
/* ... */
}
|
...