checking for overflow in C

Norman Diamond diamond at diamond.csl.sony.junet
Wed May 10 15:54:44 AEST 1989


In article <939 at garcon.cso.uiuc.edu> mcdaniel at uicsrd.csrd.uiuc.edu (Tim McDaniel) writes:

>Summary: A week of debugging may save you ten seconds of typing and
>one minute of extra run time.

Hear, hear!

>C requires that unsigned arithmetic be modulo 2**n for appropriate n;
>operations are not permitted to overflow.  Therefore, I used unsigned
>arithmetic, with a separate "int sign_bit" where necessary.

>Oh, the final stores (converting the unsigned work variables to ints)
>are trivial:
>    assert(sign_bit == 1 || sign_bit == -1);
>    if (sign_bit > 0) {
>        assert(temp <= INT_MAX);  /* or SHORT_MAX or ... */
>        }
>    else {
>        assert(temp <= INT_MIN);
>        }
>    actual = sign_bit * temp;

If you didn't find your bug in this, you either have a brain-damaged
"assert" or you didn't try very hard.  Since you carefully keep
temp >= 0, it's kind of hard for temp to be <= INT_MIN.





--
Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.co.jp at relay.cs.net)
  The above opinions are my own.   |  Why are programmers criticized for
  If they're also your opinions,   |  re-inventing the wheel, when car
  you're infringing my copyright.  |  manufacturers are praised for it?



More information about the Comp.lang.c mailing list