What does __VA_ARGS__ in a macro mean?

依然范特西╮ 提交于 2019-12-04 08:44:59

问题


/* Debugging */
#ifdef DEBUG_THRU_UART0
#   define DEBUG(...)  printString (__VA_ARGS__)
#else
void dummyFunc(void);
#   define DEBUG(...)  dummyFunc()   
#endif

I've seen this notation in different headers of C programming, I basically understood it's passing arguments, but I didn't understand what this "three dots notation" is called?

Can someone explain it with example or provide links also about VA Args?


回答1:


The dots are called, together with the __VA_ARGS__, variadic macros

When the macro is invoked, all the tokens in its argument list [...], including any commas, become the variable argument. This sequence of tokens replaces the identifier VA_ARGS in the macro body wherever it appears.

source, bold emphasis of mine.

A sample of usage:

#ifdef DEBUG_THRU_UART0
#   define DEBUG(...)  printString (__VA_ARGS__)
#else
void dummyFunc(void);
#   define DEBUG(...)  dummyFunc()   
#endif
DEBUG(1,2,3); //calls printString(1,2,3) or dummyFunc() depending on
              //-DDEBUG_THRU_UART0 compiler define was given or not, when compiling.



回答2:


It's a varadic macro. It means you can call it with any number of arguments. The three ... is similar to the same construct used in a varadic function in C

That means you can use the macro like this

DEBUG("foo", "bar", "baz");

Or with any number of arguments.

The __VA_ARGS__ refers back again to the variable arguments in the macro itself.

#define DEBUG(...)  printString (__VA_ARGS__)
               ^                     ^
               +-----<-refers to ----+

So DEBUG("foo", "bar", "baz"); would be replaced with printString ("foo", "bar", "baz")



来源:https://stackoverflow.com/questions/26053959/what-does-va-args-in-a-macro-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!