Disappearing function call

Hall marcus at ihlpl.UUCP
Fri Oct 3 03:44:59 AEST 1986


In article <357 at cullvax.UUCP> drw at cullvax.UUCP (Dale Worley) writes:
>What I want to do is to write a function call of a variable number of
>arguments:
>
>	debug(x, y, z, ...)
>
>that will generate no code when the symbol DEBUG is not defined, but
>generate a call of some function (say, debug_()) when it is.  If
>debug() always had the same number of arguments, we could use
>
>	#ifdef DEBUG
>	#define debug(x, y, z)	debug_(x, y, z)
>	#else
>	#define debug(x, y, z)	/* null */
>
>but macros aren't allowed to have a variable number of arguments.

How about this:

#ifndef	DEBUG
#define debug
#endif

and writing in the code:

	debug(a,b,c)


If DEBUG is turned on, nothing will happen to the debug statements, so a
call to debug will be produced (as you would expect).  If DEBUG isn't
defined, the symbol "debug" will be pre-processed out of existance, so
the compiler will see an expression like:

	(a,b,c)

If the arguments don't produce any side effects, I believe that most decent
compilers will not emit any code (or at least the optimizer should be able
to detect a load of a useless register.  If the debug function returns a
value that is checked, when DEBUG is turned off, the value will be the last
parameter, which will generate code, but I don't suppose that the debug
routine actually returns a value.  Simple expressions as arguments to the
debug function should also produce no code if DEBUG is turned off, but it
is possible that complex expressions could fool the compiler into generating
code for parts of the expression then throwing the result away.  One way
that this could generate code is if the optimizer has to remove the useless
loads and this is the last expression in the function (so that there isn't
a return statement).  If a value is loaded into the register that is used
for the return value, the optimizer may think that that is the return value
and thus it wouldn't think it was a useless load.

If any of the arguments have side effects or involve function calls (with
potential side effects there!), these will (and should) always be generated.
However, I don't think that it is likely that you would want to be doing
this sort of thing in a call to a debugging macro.

Are there any problems with doing this?  I suppose that some pre-processors
could choke on the parenthesis after debug in the invocation, since debug
is #defined as a parameter-less macro, but my pre-processor (SVR2) doesn't.

Marcus Hall
..!ihnp4!ihlpl!marcus



More information about the Comp.lang.c mailing list