checking for overflow in C

Kenneth Almquist ka at june.cs.washington.edu
Wed May 10 19:26:31 AEST 1989


In article <1989May9.183140.1770 at utzoo.uucp>, henry at utzoo.uucp (Henry Spencer) writes:
> In article <8143 at june.cs.washington.edu> ka at june.cs.washington.edu (Kenneth Almquist) writes:
>>> ... There is no consensus on whether the hardware checks for overflow
>>> or not....
>> If there is not a consensus, there is certainly an overwhelming majority!
>> I know the assembly languages of half a dozen machines, and they all
>> include overflow checks.
>
> But not as part of the multiply instruction.  They are extra-cost tests,
> typically at the very least a conditional branch following the multiply.
> This gets expensive when you know that your multiplies never overflow, which
> is why C compilers typically do not generate those tests.

OK, I think I see your point.  My assumption is that the cost isn't a
big issue because the programmer wouldn't test for overflow unless it
was necessary.  You would see an *occasional* test such as:

	  new C keyword
		|
		v
	if (overflow a = b * c)
		printf("Multiplication overflowed\n");
	else
		printf("%d * %d = %d\n", b, c, a);

Now of course if we added the gcc "statement within an expression"
construct to C it would be possible to write:

	if (overflow {a = b * c;
		      ... many C statements ...
		      a += c})
		printf("An overflow occurred somewhere\n");

This would generate a lot of tests, but the syntax is ugly enough to
discourage its use.  (I can't think of a cleaner syntax off hand.)

If the hardware insists on doing a trap on overflow rather than
setting a flag, there is a big jump in the cost, but only when the
overflow actually occurs, which we can assume will be rare.  More
serious is that on such a machine, overflow checks would require run
time support, and therefore might not be available in a non-hosted
environment.  One of the nice features of C is that virtually all the
features requiring run time support are provided through library
routines, so in a non-hosted environment you simply write your own
implementations of these routines, or don't call them.
				Kenneth Almquist



More information about the Comp.lang.c mailing list