string argument to assert macro

Marc Wachowitz I403%DMAFHT1.BITNET at cunyvm.cuny.edu
Thu Mar 14 05:42:33 AEST 1991


Recently someone asked how to correctly output a string through an
assert macro. The answer is that there is (as far as i know) no
general way to do that with old (K&R) C preprocessors. If you have
an ANSI conformant preprocessor, it's simple (you may be able just to
replace your local CPP with that from GNU, which should be fairly easy
to port, even if no port of the whole GCC exists for your system).
An ANSI-C conformant implementation of <assert.h> may be the following:

/* <assert.h> - assertion checking */

extern
void assert_failed(const char *_a, const char *_f, unsigned long _l);
/* say that assertion _a failed on line _l of file _f; assuming that
   an unsigned long is big enough to hold every reasonable line
   number :-), then abort().
*/

#undef assert
/* allow several inclusions with different settingsof NDEBUG */

#ifdef NDEBUG /* disable assertion checking */
#define assert(a) ((void)0)
#else /* enable assertion checking */
#define assert(a) ((a)?(void)0:_assert_failed(#a,__FILE__,__LINE__))
#endif /* NDEBUG */
/* end of <assert.h>
The trick is that the single # operator (in front of a) forms a string
from (the expanded form of) a, prepending backslash-characters where
needed to form a correct string literal.

Hope that helps.
    Marc



More information about the Comp.unix.internals mailing list