Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!uxc!garcon!uicsrd.csrd.uiuc.edu!mcdaniel From: mcdaniel@uicsrd.csrd.uiuc.edu (Tim McDaniel) Newsgroups: comp.lang.c Subject: Re: How to multiply two ints and check Message-ID: <1059@garcon.cso.uiuc.edu> Date: 19 May 89 04:29:52 GMT References: <434@skye.ed.ac.uk> <4700038@m.cs.uiuc.edu> Sender: news@garcon.cso.uiuc.edu Reply-To: mcdaniel@uicsrd.csrd.uiuc.edu (Tim McDaniel) Organization: Center for Supercomputing R&D (Cedar), U. of Ill. Lines: 20 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}