How to multiply two ints and check

Tim McDaniel mcdaniel at uicsrd.csrd.uiuc.edu
Fri May 19 14:29:52 AEST 1989


In article <4700038 at m.cs.uiuc.edu> robison at m.cs.uiuc.edu writes:
>There is a much simpler, faster, and machine-independent way to check
>for multiplication overflow --- check the product by division.  To wit:
...
>			int product = n1*n2;
>			if( n2!=0 && product/n2 != n1 )

(1) The overflow happens before the check.  Bad news if your program
is aborted unrecoverably on overflow.
(2) Divide can overflow.  Consider INT_MIN/-1 on a 2s-complement
machine.

--
"6:20 O Timothy, keep that which is committed to thy trust, avoiding
profane and vain babblings, and oppositions of science falsely so
called: 6:21 Which some professing have erred concerning the faith."

Tim, the Bizarre and Oddly-Dressed Enchanter  |  mcdaniel at uicsrd.csrd.uiuc.edu
            {uunet,convex,pur-ee}!uiucuxc!uicsrd!mcdaniel
            mcdaniel%uicsrd@{uxc.cso.uiuc.edu,uiuc.csnet}



More information about the Comp.lang.c mailing list