ANSI assert

Mike Coleman coleman at twinsun.com
Sun Sep 9 02:34:42 AEST 1990


joe at proto.COM (Joe Huffman) writes:
>My concern is when NDEBUG is defined.  I have many places in my code where I
>do something like the following:
>  assert(tree_init() == OKAY);

>My definition of assert with debugging turned off looks like:

>#define assert(test) ((void)(test))

>Am I in error for doing this? 

Yes, at least the way I understand things.  Nothing which is necessary for the
correctness of your program should be put in an assert.  Only expressions
necessary to *test* the assertion should be in the assert.  This is an easy
mistake to make; I still do it occasionally.  So, the correct version of the
code you give above (as I read it) would be

	result = tree_init();
	assert(result == OKAY);

The point of having the assert in the first place is that you can put checks
for correctness in your program which are extremely expensive, and then remove
them simply by defining NDEBUG.  For example, imagine this piece of code in a
malloc implementation:

	assert(validate_heap());  /* an expensive function which validates the
					heap to within an inch of its life. */

The version of assert you assume does not give the desired effect here.  In
particular, casting an expression to 'void' does *not* allow the compiler to
throw it away, in and of itself.

In any case, if you want this behavior, just define your own macro.  But
please, don't call it 'assert'.

Hope this helps.
-- 
Nothing's ever late when it's measured in Programmer's Time: ++ coleman
  |     |     |     |     |     |     |     |     |          ++ @twinsun.com
BEGIN  1/2   2/3   3/4   4/5   5/6   6/7   7/8   8/9  (etc)  ++ @cs.ucla.edu



More information about the Comp.std.c mailing list