#defines with variable # arguments

Larry Yaffe lgy at pupthy2.PRINCETON.EDU
Sat May 14 14:56:42 AEST 1988


In article <2633 at tekcrl.TEK.COM> terryl at tekcrl.tek.com writes:
 >In article <2855 at phoenix.Princeton.EDU+ (lgy at pupthy2.PRINCETON.EDU) I wrote:
 >+
 >+    Are there any versions of cpp which allow one to define macros which
 >+accept variable numbers of arguments?  I keep wishing for this every time
 >+I try to move code developed using sysV sprintf to a BSD system, so that
 >+I could do something like:	[example deleted]
 >
 >     I came across this kludge years ago, hope it helps:
 >#define	sprintf(prf)	{ Sprintf prf }
 >
 >     The TRICK is to ADD an extra level of parentheses, using it like thus:
 >
 >		sprintf( (buffer,"<what-ever-string-you-want>",<varargs>) );
 >
 >This makes cpp THINK there is only one argument to the macro; I know you
 >don't want to muck with the sources and just want to put in the #define

	Right!!

 >and be done with it, but this is the only way I know of.

    A number of people suggested variants of the above.  Unfortunately,
all of these approaches require manual editing of (large amounts of) existing
source code.  The whole point of the exercise is to be able to automate the
conversion between sysV & BSD versions of sprintf.  Regrettably, such a
stupid little inconsistency (the difference in return values) cannot be
automatically fixed using any combination of cpp, sed, or awk.

    Several other people pointed out that one shouldn't ever use the
return value of sprintf if you want maximally portable code.
True, but rewritting existing code is SO much fun :-).

 >+    Does anyone know why the folks at Berkeley chose to have their
 >+sprintf return its first argument, instead of the number of characters
 >+printed?  I can't think of any good reason for this choice, since it
 >+throws away valuable information (the # of characters printed) which
 >+is painful to reacquire.
 >
 >     How painful is a strlen???? (I.E. I really don't understand your
 >complaint).

    Well, since every implementation of sprintf I've seen counts the
number of characters printed internally, its irritating if you have to
call strlen just to recompute information that was easily available but
thrown away.  And its quite possible for the extra call to strlen to
take nearly as long as the sprintf.  If you're calling sprintf a LOT of
times, adding a call to strlen after each sprintf can be very significant.

------------------------------------------------------------------------
Laurence G. Yaffe			Internet: lgy at pupthy.princeton.edu
Department of Physics			Bitnet:   lgy at pucc
Princeton University			UUCP:     ...!princeton!pupthy!lgy
PO Box 708, Princeton NJ 08544



More information about the Comp.unix.wizards mailing list