Saturday, August 8, 2009

__VA__ARGS__

How to create a macro which takes variable number of arguments?

I had to do this as I wanted to replace a printf with a common debug function that can be turned on or off in the runtime. Besides, I wanted to print local variables from that function. The simplest way was to define a macro that will replace the printf.

However, printf takes variable number of arguments. How do I handle that in a macro? The answer was __VA_ARGS__. Using this, you can replace (more or less) any printf with something like what is shown below.


#define DBG_PRN(x,...) do {\
if ( is_debug_on() )\
{\
printf(x,__VA_ARGS__);\
}\
}while(0);


The downside is, you need to have minimum of two arguments for printfs. If you do not have minimum two arguments, you will get a compilation error.I solve this by providing a dummy variable.

The gcc way of doing this is different. That depends on the the pre-processor operator ## to achieve this. This method will help you solve the empty argument issue.

No comments: