Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to write macros with a variable argument list in visual C++?

As far as I know, in gcc you can write something like:

#define DBGPRINT(fmt...) printf(fmt);

Is there a way to do that in VC++?

like image 738
Domo Avatar asked Sep 15 '08 17:09

Domo


People also ask

Can we pass a macro as argument?

Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like.

What is variable argument list in C?

Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.

What are the macros that are designed to support variable length arguments?

To support variable length arguments in macro, we must include ellipses (…) in macro definition. There is also “__VA_ARGS__” preprocessing identifier which takes care of variable length argument substitutions which are provided to macro.

How do I use variadic macros?

To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.


2 Answers

Yes but only since VC++ 2005. The syntax for your example would be:

#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)

A full reference is here.

like image 169
Gareth Simpson Avatar answered Sep 23 '22 06:09

Gareth Simpson


Yes, you can do this in Visual Studio C++ in versions 2005 and beyond (not sure about VS 2003). Take a look at VA_ARGS. You can basically do something like this:

#define DBGPRINTF(fmt, ...)  printf(fmt, __VA_ARGS__)

and the variable arguments to the macro will get passed to the function provided as '...' args, where you can then us va_args to parse them out.

There can be weird behavior with VA_ARGS and the use of macros. Because VA_ARGS is variable, that means that there can be 0 arguments. That might leave you with trailing commas where you didn't intend.

like image 25
Mark Avatar answered Sep 22 '22 06:09

Mark