Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!mips!apple!voder!nsc!amdahl!JUTS!ruts!msh30 From: msh30@ruts.ccc.amdahl.com (Mark Hahn) Newsgroups: comp.lang.c Subject: Re: Question about assertion macro Message-ID: <17N902t808i701@JUTS.ccc.amdahl.com> Date: 1 Jun 91 00:57:52 GMT References: <1991May29.152228.27611@viewlogic.com> Sender: netnews@ccc.amdahl.com Reply-To: msh30@RUTS.ccc.amdahl.com (PUT YOUR NAME HERE) Organization: Amdahl Corporation, Sunnyvale CA Lines: 48 >From: greg@suntan.viewlogic.com (Gregory Larkin) > > >Hi there, > >I would like to construct an assertion macro so that I >can print the exact condition that failed as a string. > >Here is the way I call the macro: > >ASSERT(foo != NULL, "Unexpected NULL pointer"); > >And here is how it is currently defined: > >#define ASSERT(relation, msg) { if(!(relation)) { \ > printf("ASSERTION FAILED: File %s Line %d %s\n",\ > __FILE__, __LINE__, msg); \ > exit(FatalError); } } > >I would like to expand the macro so that I can print the message as: > >ASSERTION FAILED: foo != NULL, File xxxx Line yyyy Unexpected NULL pointer > >How can I print the string "foo != NULL" without passing in the test as >a string. Can I print the test directly as a string somehow? > >Thanks for any help, >-- >Greg Larkin (ASIC Engineer)|"This is a fragile ball we are living on; >Viewlogic Systems, Inc. |it's a miracle and we are destroying it.." >293 Boston Post Road West |Peter Garrett, Midnight Oil >Marlboro, MA 01752 (greg@Viewlogic.COM) #define ASSERT_ARG(relation, msg, action) \ if ( !(relation) ) { \ printf("ASSERTION FAILED: File %s Line %d %s %s\n",\ __FILE__, __LINE__, "relation", msg);\ action; \ } /* if assertion failed */ should work in standard C; I'm not sure about ANSI C, though. This version has the advantage of being able to specify a C statement as an action to be taken rather than calling exit(), which is useful if you need to clean up some things first. Usage: ASSERT_ARG( foo != NULL, "Unexpected NULL pointer", cleanup_routine(arg1, arg2, ..., argn) );