home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / programm / 2441 < prev    next >
Encoding:
Text File  |  1992-08-23  |  2.2 KB  |  48 lines

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