Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!unmvax!deimos.cis.ksu.edu!rutgers!ukma!husc6!rice!uw-beaver!uw-june!ka From: ka@june.cs.washington.edu (Kenneth Almquist) Newsgroups: comp.lang.c Subject: Re: checking for overflow in C Message-ID: <8172@june.cs.washington.edu> Date: 10 May 89 09:26:31 GMT References: <13367@dartvax.Dartmouth.EDU> <1989May6.224226.22085@utzoo.uucp> <1989May9.183140.1770@utzoo.uucp> Organization: U of Washington, Computer Science, Seattle Lines: 46 In article <1989May9.183140.1770@utzoo.uucp>, henry@utzoo.uucp (Henry Spencer) writes: > In article <8143@june.cs.washington.edu> ka@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