Path: utzoo!mnetor!uunet!husc6!necntc!ima!haddock!karl From: karl@haddock.ISC.COM (Karl Heuer) Newsgroups: comp.lang.c Subject: optimizing assert Message-ID: <2276@haddock.ISC.COM> Date: 14 Jan 88 23:34:22 GMT References: <2942@hall.cray.com> <531@cresswell.quintus.UUCP> Reply-To: karl@haddock.ima.isc.com (Karl Heuer) Organization: Interactive Systems, Boston Lines: 38 In article <531@cresswell.quintus.UUCP> ok@quintus.UUCP (Richard A. O'Keefe) writes: >Is there any reason why C compilers should not be allowed to assume the >truth of assertions even in the presence of NDEBUG? I like the idea. There are a few problems; let's formalize. Subproposal A: Whether or not NDEBUG is set, assert() shall always evaluate its argument for side effects. Rationale: Although current implementations do not conform to it, the proposal is easy to implement ("#define assert(e) ((void)(e))") and makes assert() more useful ("assert(getchar() == '\n')"). This should not break any existing code, because anything which depends on the argument *not* being evaluated will behave differently depending on whether NDEBUG is set or not. Subproposal B: The macro shall expand into a void expression. Rationale: This would guarantee that it is legal in an expression context, e.g. "y = 1.0 / (assert(x!=0.0), x)". This isn't critical, but it helps prevent surprising behavior in some contexts. Subproposal C: If the argument of assert() is true (compares unequal to zero), then the macro returns no value. Else, if the NDEBUG macro is not defined, then a message is printed and the abort() function is invoked. (At this point we still agree with the dpANS; the next statement is the proposal.) Else, the behavior is undefined. Rationale: One normally defines NDEBUG for optimization. The code has been tested without NDEBUG and verified to be correct; the programmer no longer wants the overhead of an explicit run-time check. If the behavior in the third case is undefined, the compiler may be able to generate better code by assuming that the assertion is true. Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint ________ Note: according to Walter Bright's article <1459@dataio.Data-IO.COM>, it seems that current optimizer technology won't handle anything much more complex than "assert(x == 3)" or "assert(x == y)".