assert(): a "tutorial"
Tim McDaniel
mcdaniel at amara.uucp
Fri Apr 13 09:23:24 AEST 1990
u096000 at lanl.gov (Roger A. Cole) wrote a good article about assert().
assert() doesn't get enough respect: it can be a BIG lifesaver, and a
significant help in documentation! (As Roger pointed out.)
In the article, he gave a definition
#ifdef DEBUG
# define assert(expr) ((void)((expr) || assertFail(__FILE__, __LINE__)))
#else
# define assert(expr)
#endif
However, one of the examples given was
assert(strlen(name) < 20), printf("%s\n", name);
If DEBUG were not defined, this would expand to
, printf("%s\n", name);
which is not syntactically valid. Making the second choice be
# define assert(expr) ((void) 0)
would suffice.
(Personally, I prefer to print the expression that failed, which could
help if I wrote two assertions on one line. I also like to give a
constant string as an explanation argument, for non-obvious checks:
assert(frobozz(queue) != xyzzy(reg), "pipeline lost a datum");
If, instead, you put an explanatory comment there, the effect would be
more-or-less identical, but requiring a second argument forces the
programmer to provide an explanation. Personal style.)
--
Tim McDaniel
Applied Dynamics International, Ann Arbor, MI
Internet: mcdaniel%amara.uucp at mailgw.cc.umich.edu
UUCP: {uunet,sharkey}!amara!mcdaniel
More information about the Comp.lang.c
mailing list