Newsgroups: comp.lang.c Path: utzoo!henry From: henry@utzoo.uucp (Henry Spencer) Subject: Re: checking for overflow in C Message-ID: <1989May9.182628.1656@utzoo.uucp> Organization: U of Toronto Zoology References: <13367@dartvax.Dartmouth.EDU> <472@cbnewsh.ATT.COM> Date: Tue, 9 May 89 18:26:28 GMT In article <472@cbnewsh.ATT.COM> rkl@cbnewsh.ATT.COM (kevin.laux) writes: > Basically, it is impossible to Overflow when multiplying two integers. Sorry, wrong. >If you multiply two 8-bit integers, the result will not exceed 16-bits. >Likewise, two 16-bit ints won't exceed a 32-bit result. Except that C multiplication, and the multiply instructions on some (not all) modern machines, multiply two 16-bit numbers to give a 16-bit number, or two 32-bit numbers to give a 32-bit number. > So, except for the special case above, the CPU's multiply instruction >(ie. the multiplication algorithm designed into the hardware/firmware/ >microcode)will never Overflow and will return the appropriate result. It is up to you >to provide a variable large enough to hold the result... You are assuming (a) that the CPU *has* a multiply instruction (some don't), (b) that it gives double-width results, and (c) that it does not trap an overflow. -- Mars in 1980s: USSR, 2 tries, | Henry Spencer at U of Toronto Zoology 2 failures; USA, 0 tries. | uunet!attcan!utzoo!henry henry@zoo.toronto.edu