Graphics Reference
In-Depth Information
different, overflow occurred. (With some care, single- or double-precision floats could
also be used to test for integer operation overflows.) If the type is already the largest
supported native integer type, this will not work, however. As an illustration of how
overflow can be tested for without going to a larger integer type, consider the addition
of unsigned integers a and b . The overflow of c
=
a
+
b can be detected by testing the
input arguments in the manner
bool overflow = (a > ∼b);
unsigned intc=a+b;
or by testing the result (where overflow occurs if the result is smaller than either
argument):
unsigned intc=a+b;
bool overflow = (c < a);
For signed integers a and b , the overflow test becomes a little more complicated. An
early test can be done by comparing the arguments against INT_MAX and INT_MIN
based on sign as
bool overflow = (a>0?(b>INT_MAX - a) : (b < INT_MIN - a));
signed intc=a+b;
or after the addition has taken place by detecting if a and b have the same sign and the
result has opposite sign (however, note that testing after the fact relies on behavior
unspecified by the language standard with respect to overflow):
signed intc=a+b;
bool overflow = ((a b)>=0&&(b c) < 0);
Similar overflow tests can be devised for subtraction and multiplication.
Overflow (and therefore overflow testing) can be avoided by allotting enough
bits to hold all intermediate and the final result of a calculation exactly. This often
requires implementing extended-precision operations. Extended-precision addition
and subtraction can often be efficiently implemented using native support in the CPU
of a carry flag (or similar mechanism). Assuming the widest available integer type is
32 bits, a high-level implementation of unsigned 64-bit addition may be performed
as follows.
 
Search WWH ::




Custom Search