...
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 | ||||
---|---|---|---|---|
| ||||
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 | ||||
---|---|---|---|---|
| ||||
long i = /* Expression that evaluates to the value 32767 */; /* ... */ /* No test is necessary; i is known not to overflow. */ /* expression involving i + 1 */ |
...