checking for overflow in C

Henry Spencer henry at utzoo.uucp
Wed May 10 04:26:28 AEST 1989


In article <472 at cbnewsh.ATT.COM> rkl at 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 at zoo.toronto.edu



More information about the Comp.lang.c mailing list