Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this noncompliant example, i + 1 will overflow on a 16-bit machine. The C standard allows signed integers to overflow and produce incorrect results. Compilers can take advantage of this to produce faster code by assuming an overflow will not occur. As a result, the if statement that is intended to catch an overflow might be optimized away.

Code Block
bgColor#ffcccc
langc
int i = /* Expression that evaluates to the value 32767 */;
/* ... */
if (i + 1 <= i) {
  /* handle overflow */
}
/* expression involving i + 1 */

...

Using a long instead of an int is guaranteed to accommodate the computed value.

Code Block
bgColor#ccccff
langc
long i = /* Expression that evaluates to the value 32767 */;
/* ... */
/* No test is necessary; i is known not to overflow. */
/* expression involving i + 1 */

...