Detecting overflow

John F Carr jfc at athena.mit.edu
Tue May 23 15:36:08 AEST 1989


In article <731 at sdrc.UUCP> scjones at sdrc.UUCP (Larry Jones) writes:
>If a and b are both integers, then the expression "a"
>does give the same result as "(a*b)/b" except when "(a*b)/b"
>overflows.  If it overflows, the results are undefined and
>getting the "correct" answer without generating an overflow is
>certainly an allowable response to undefined behavior.

If they are unsigned integers, this optimization is not possible,
since overflow is ignored (i.e. given n bit words,

  (2 * (2^n - 1)) / 2 == 2^(n-1) - 1 

is required with unsigned math [becuase the intermediate value,
2*(2^n - 1) must be truncated to 2^n - 2], while the true answer is

  (2 * (2^n - 1)) / 2 ==  2^n - 1

).

    --John Carr (jfc at athena.mit.edu)

   John Carr             "When they turn the pages of history,
   jfc at Athena.mit.edu     When these days have passed long ago,
   bloom-beacon!          Will they read of us with sadness
   athena.mit.edu!jfc     For the seeds that we let grow?"  --Neil Peart



More information about the Comp.lang.c mailing list