home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!gatech!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Subject: Re: Detecting Integer Overflow/Underflow
- Message-ID: <1992Aug23.192531.28982@hubcap.clemson.edu>
- Organization: Clemson University, Clemson SC
- References: <1992Aug21.182206.15853@progress.com> <51147@seismo.CSS.GOV>
- Date: Sun, 23 Aug 1992 19:25:31 GMT
- Lines: 37
-
- In article <51147@seismo.CSS.GOV> black@seismo.CSS.GOV (Mike Black) writes:
- >In article <1992Aug21.182206.15853@progress.com> erf@progress.com writes:
- >>
- >>Given: Two numbers (integers) of the same bit-width (e.g., they're
- >>both stored as 16-bit integers), and writing in "C" (with no access to
- >>the assembly language of the machine; it must be portable!) is it
- >>possible to write code to detect whether the result of adding,
- >>substracting or multiplying the two numbers will result in overflow or
- >>underflow? The detection can be done either before or after the
- >>operation. It should, of course, be as efficient as possible, but any
- >>solutions are welcome.
- >>
- >
- >I already mailed a reply to this, but after seeing the postings thought
- >I should add it here:
- >
- >Since the person wants a solution that is portable, in C, and addresses
- >addition, subtraction, and multiplication a solution is quite
- >straightforward. USE LONGS! Simply caste the operands into longs,
- >perform the math, and check the answer. If the answer is within 16-bit
- >limits (signed or unsigned) return the answer else set overflow.
-
- Well, the original poster did ask for a *portable* solution. You have
- assumed that longs are always larger than ints (or shorts), which is
- not true in general.
-
- Another point is that for full portability, the test for overflow must
- be done *before* the operation, since some machines will trap on
- integer overflow. On a two's complement machine, you could do the
- addition in *unsigned* arithmetic, cast the result back to int, then
- check the sign of the result (if both operands are positive). If you
- want to allow the possibility of a result equal to INT_MIN (from
- limits.h) on such a machine, the test is slightly more complicated.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-