[comp.lang.c] How to multiply two ints and check

robison@m.cs.uiuc.edu (05/18/89)

Re: "How to multiply two ints and check"

There is a much simpler, faster, and machine-independent way to check
for multiplication overflow --- check the product by division.  To wit:

	int vmul(n1,n2,p_ovf)
		int n1,n2;
		int *p_ovf;
		{
			int product = n1*n2;
			if( n2!=0 && product/n2 != n1 )
				*p_ovf = YES;
			else
				*p_ovf = NO;
			return product;
		}

This code doesn't need to know sizeof(int), and even works on decimal machines!

Arch D. Robison
University of Illinois at Urbana-Champaign

UUCP: {pur-ee,convex}!uiucdcs!robison
Internet: robison@CS.UIUC.EDU

mcdaniel@uicsrd.csrd.uiuc.edu (Tim McDaniel) (05/19/89)

In article <4700038@m.cs.uiuc.edu> robison@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@uicsrd.csrd.uiuc.edu
            {uunet,convex,pur-ee}!uiucuxc!uicsrd!mcdaniel
            mcdaniel%uicsrd@{uxc.cso.uiuc.edu,uiuc.csnet}

gwyn@smoke.BRL.MIL (Doug Gwyn) (05/20/89)

In article <4700038@m.cs.uiuc.edu> robison@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.  ...

Nope, for portability you have to avoid signed-integer overflow in
the first place.  The overflow might (and does in some implementations)
cause an ABEND.

chris@mimsy.UUCP (Chris Torek) (05/20/89)

In article <4700038@m.cs.uiuc.edu> robison@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.

Alas, by then it is too late: your program has crashed.  (Not on a
VAX, nor on a Sun nor a Tahoe nor Encore, but on some machines, yes.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris