checking for overflow in C

Henry Spencer henry at utzoo.uucp
Sun May 7 08:42:26 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...

C unfortunately has to be close to the hardware of a wide variety of
machines.  There is no consensus on whether the hardware checks for overflow
or not.  C generally prefers to reflect the underlying hardware rather
than trying to hide it, so this lack of consensus shows to the programmer.
C does not promise that overflow will be detected at all.  Nor does C
promise that overflow *won't* be detected; it might abort your program, or
just do strange things.  For reliable and portable code, you must do the
check yourself, in advance (and be careful that your overflow check can't
itself cause 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