checking for overflow in C

kevin.laux rkl at cbnewsh.ATT.COM
Tue May 9 02:27:23 AEST 1989


In article <13367 at dartvax.Dartmouth.EDU>, shallit at eleazar.dartmouth.edu (Jeffrey Shallit) writes:
> Fans of C frequently boast that it is "very close to the machine".  Since
> I'm a relative newcomer to the language, perhaps someone could enlighten
> me about the officially approved way of checking overflow when multiplying
> two integers.  Or is doing (i) a pre-multiply test to ensure the arguments
> aren't too big or (ii) a post-division step to ensure the accuracy of the
> result the only portable way of doing this?
> 

	Basically, it is impossible to Overflow when multiplying two integers.
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.

	Now, if you're asking if it's possible to Truncate, why of course it
is.  Just take two, say 16-bit ints, multiply them and assign the result to
to an 8-bit char :-).

	The only time you might have a problem it when you're multiplying
two longs with large values together.  If your longs are 32-bits, then the
result may need to be expressed in 64-bits.  You would have to call a
function designed to handle such cases and that would return two 32-bit longs,
one being the Most Significant part, the other being the Least Significant
part.

	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.  And even for the
special case, you still cannot get an overflow; you just get back the pieces
which you now must manipulate appropriately.

--rkl



More information about the Comp.lang.c mailing list