Variable arguments in macros

Rex Jaeschke rex at aussie.UUCP
Tue Apr 25 10:50:36 AEST 1989


> I've been trying to find a way to have macros with variable numbers of
> arguments in ANSI C, and I don't think it can be done.  I'm hoping that
> I'm wrong and that someone can tell me how to do it.

I have a solution but it isn't particularly elegant.

When I read your question I recalled working on related issues in 
X3J11 in a public comment review subgroup, re parens and commas as 
preprocessing tokens in macro calls.

First my (inelegant) solution then a discussion. This program works 
fine on WATCOM's V7 DOS compiler which, according to my test suite, is 
pretty darn close to X3J11's latest draft. It also works on Microsoft 
V5.1 but not Turbo C V2.

#include <stdio.h>

#define C ,

#define PR(s) fprintf(stderr, s)

main()
{
	PR("test1\n");
	PR("test2 %d\n" C 10);
	PR("test3 %d %d\n" C 10 C 100);
}

The output is:

test1
test2 10
test3 10 100

Obviously, the inelegant part is the use of the macro C. It's hard to 
call it anything meaningful yet not have it get in the way of 
readability.

According to the latest draft page 90 lines 36 and 38, and page 91 
line 4, the left and right parens and commas separating actual 
arguments (not those commas inside parens), MUST be preprocessing 
tokens. They CANNOT come into being as the result of macro expansion 
UNLESS as a result of the token pasting operator ##. As such, the C 
macro calls in my example are expanded to commas but the commas are all 
part of the one big argument to PR.

Aparently, numerous preprocessors used to (and probably still do) 
allow the parens and commas to be created by macro expansion. ANSI 
does not permit this.

Rex

----------------------------------------------------------------------------
Rex Jaeschke     | C Users Journal     |  Journal of C Language Translation
(703) 860-0091   | DEC PROFESSIONAL    |1810 Michael Faraday Drive, Suite 101
uunet!aussie!rex | Programmers Journal |     Reston, Virginia 22090, USA
----------------------------------------------------------------------------



More information about the Comp.std.c mailing list