# Variable argument Macro

This topic is 5127 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

does anyone know how to make a macro that takes multiple arguments? (for use with functions that have "..." or variable arguments )

##### Share on other sites
I don't quite understand your question. Is it that you need to create functions with variable arguments and don't know how? If that's the case, look at this OpenGL tutorial on NeHe: click. Take a look at the glPrint function. In it he uses variable arguments. This is how I learned. You will need stdarg.h. If you need further help, consult that msdn pages or post some more. Sorry if this isn't what you needed.

##### Share on other sites
It's not a part of standard C++, nor is it in C89, but I think C99 may have some support for it(not a lot of compilers supporting C99 out there, though). GCC lets you define variadic macros like this:

#define PRINTF_DEBUG( format, args...) xprintf( putc_debug, format, args )

VC++ does not, to my knowledge, have any support for variadic macros.

##### Share on other sites
C99 does indeed define syntax for variadic macros, although I'm not sure how widely supported it is.

The definition for a variadic macro is similar to a variadic function:

#define MACRO(a, b, ...) // etc.

and the unnamed parameters are referenced by "__VA_ARGS__".

You need to be a bit careful when working with variadic macros. I'll quickly illustrate a simple problem: consider the following macro, designed to call a constructor for some type.

#define CONSTRUCT(typename, var, ...)     CONSTRUCT_##typename(var, __VA_ARGS__)

If no parameters are provided to the macro, however, it expands to (say):

CONSTRUCT_WINDOW(mainwnd, )

which is incorrect. C99 thus allows the token concatenation operator, "##", to omit a preceding comma if the operator's right-hand side is empty. So by changing the macro definition to

#define CONSTRUCT(typename, var, ...)     CONSTRUCT_##typename(var, ## __VA_ARGS__)

the above example would expand to

CONSTRUCT_WINDOW(mainwnd)

as desired.

##### Share on other sites
err... i just want a to make a macro that uses swprintf and _scwprintf, but you would only have to write it in once...

something like:

PString result = new String ( false, _scwprintf ( formatstring, args ) );swprintf ( *result, formatstring, args  );

where args could be multiple arguments...

##### Share on other sites
Variadic macros are also standard in C; the syntax has been given so I don't need to go into that.

##### Share on other sites
look into boost.format

##### Share on other sites
This works, but is a bit ugly:

// The define:
#define MYPRINTF(args) printf args

// Usage: Note the double-bracketing.
MYPRINTF(("num=%d\n", num));

Tricky huh?

james

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633654
• Total Posts
3013170
×