In Other Spaces
The page you were looking for may have moved to another space:
-
MSC21-C. Use robust loop termination conditions
(SEI CERT C Coding Standard)
C defines <, >, <=, and >= to be relational operators, and it defines == and != to be equality operators. 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 to use an equality operator (such as !=). Noncompliant Code Example (Equality Operators) This noncompliant code example appears to have five iterations, but in fact, the loop never terminates: size_t i; for (i = 1; i != 10; i += 2) { /* ... */ } Compliant Solution (Relational Operators) Using the relational operator <= instead of an equality operator guarantees loop termination: size_t i; for (i = 1; i <= 10; i += 2 ) { /* ... */ } 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: void f(size_t begin, size_t end) { size_t i; for (i = begin; i != end; ++i) { /* ... */ } } Compliant Solution (Relational Operators) Again, using a relational operator instead of equivalence guarantees loop termination. If begin >= end, the loop never executes its body.</)></,></=,>...