Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: c/int/size_t/a

...

This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.

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

...

Using the relational operator <= instead of an equality operator guarantees loop termination.

Code Block
bgColor#ccccff
intsize_t i;
for (i = 1; i <= 10; i += 2 ) {
  /* ... */
}

...

Code Block
bgColor#ffcccc
void f(intsize_t begin, intsize_t end) {
  intsize_t i;
  for (i = begin; i != end; ++i) {
    /* ... */
  }
}

...

Code Block
bgColor#ccccff
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
bgColor#ffcccc
void f(intsize_t begin, intsize_t step) {
  intsize_t i;
  for (i = begin; i <= INTSIZE_MAX; i += step) {
    /* ... */
  }
}

...

Code Block
bgColor#ccccff
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
bgColor#ccccff
intsize_t i;
for (i = 1; i == 5; ++i) {
  /* ... */
}

...