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++?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With