Detecting overflow
Ken Johnson
ken at aiai.ed.ac.uk
Thu May 18 20:58:56 AEST 1989
Since I posted a C program which detects overflow in int multiplication
at immense cost in time terms, I received the following solution
by e-mail:
if ( a != 0 && (a * b)/b == a) { /* No overflow */ }
My first thought is the first test should really be applied to b,
not a, to prevent overflow, giving
if ( b != 0 && (a * b)/b == a) { /* No overflow */ }
However, this is not always going to work. Consider the case of
a = 512 (0x200), b = 64 (0x40). Then in 16-bit arithmetic,
a != 0 is true
b != 0 is true
(a * b) = 0x8000 (overflowing) but 0x8000/0x40 = 0x200
...so I don't think this is guaranteed to work either.
A further example would be 521 * 63 (0x209 * 0x3f).
--
Ken Johnson, AI Applications Institute, 80 South Bridge, Edinburgh EH1 1HN
E-mail ken at aiai.ed.ac.uk, phone 031-225 4464 extension 212
Half of what I have said in this article is rubbish. I don't know which half.
More information about the Comp.lang.c
mailing list