SUMMARY #define DEBUG (medium long)

Jeffrey Adam Gordon gordon at hermod.cs.cornell.edu
Fri May 4 11:43:32 AEST 1990


Thanks to all who have replied and posted.  I'm getting a lot of
repeated suggestions at this point so here's a summary (the first is
the one I have chosen to use.  I prefer it because it does not leave
any dead code (except a semicolon) lying around and does not rely on a
smart compiler optimizing things away.
-----------------------------------------------------------------------
The most common thing I've seen goes something like:

#ifdef DEBUG
#define DPRINT(x) printf x
#else
#define DPRINT(x)
#endif

then in your code do:

    DPRINT(("stuff %d\n", abc));

note that the double paren's are crucial, it makes 1 arg for the
preprocessor, which either comes after printf or is discarded.
----------------------------------------------------------------------
another way would be to use something like this:

#define DEBUG 0
...
if (DEBUG) printf(....);
...

if your compiler is worth anything, it should optimize out the printf if
DEBUG is 0.  if you set DEBUG to 1 at the compile line, then the printf's
will be in place, and the compiler should still optimize out the "if" since
it is always true.
-----------------------------------------------------------------------
#ifdef DODEBUG
#   define DEBUG printf
#else
#   define DEBUG (void)
#endif DODEBUG

Now when you say

    DEBUG(format, var1, var2, var3);

it expands to one of

    printf(format, var1, var2, var3);

or

    (void)(format, var1, var2, var3);

Both of which are legal statements; the first is a function call, the
second is a parenthesized comma-expression.  Any reasonable compiler will
detect that the second form can be completely optimized out, since the
value is never used (in fact, it's explicitly thrown away).

One effect of this, which may be considered either a drawback or an
advantage depending on your point of view, is that if you accidentally
use an operation that has side effects in a DEBUG statement, that
operation will be executed regardless of the definintion of DODEBUG; the
compiler is obligated not to eliminate side-effected sub-expressions from
the comma-expression.  On the other hand, side effects should still be
avoided, because the *order* of evaluation may differ for function param
lists and comma-exprs.
-----------------------------------------------------------------------
>
	#define DEBUG1(x)	printf(x)
	#define DEBUG2(x,y)	printf(x,y)
	#define DEBUG3(x,y,z)	printf(x,y,z)

etc.  That's the best I've seen so far.  It's ugly, and requires knowing lots
of names, but it works.
-----------------------------------------------------------------------

Some solutions also had a debug level but this was more than I needed.

Thanks all.

- Jeff



More information about the Comp.lang.c mailing list