[net.bugs.v7] overflow in C once more

henry (05/14/82)

As several people pointed out, I goofed in my previous article:  the odd
results I observed were the result of an argument to printf becoming long
without warning.  I ran across (and misinterpreted) that effect in the
course of investigating a less spectacular but still interesting boobytrap
in C's handling of overflows.  Consider:

	printf("%u %u\n", (unsigned)(56*1024/64), (unsigned)(57344/64));

This prints two different numbers, because 56*1024 overflows into the
sign bit and this affects the division that follows.  57344 does not
have this problem because the arithmetic is quietly done using long int,
which eliminates the overflow.  The moral of the story is, be careful
when making your compile-time arithmetic explicit:  it makes the code
clearer, but the overflow hazard on 16-bit machines is omnipresent.
It is very hard to spot such problems when the actual numbers involved
are buried in several levels of #defines.