Variadic functions with unknown argument count
One of my colleagues came across a peculiar problem. She had to write an API that accepts variable number of arguments, but number of arguments won’t be passed in the arguments list. She cracked it intelligently with following hack.
Heart of this hack is a macro that can count the number of arguments passed to it. It has a limitation. Maximum number of arguments can be passed to this macro should be known. For example, if maximum number of arguments can be passed is 5, the macro will look like,
#define COUNT5(...) _COUNT5(__VA_ARGS__, 5, 4, 3, 2, 1)
If you want your macro to count 10 or lesser arguments,
#define COUNT10(...) _COUNT10(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Let me explain it. Consider below macro call. It will expand like this.
COUNT5(99, 98, 97);
The three arguments passed to
COUNT5 will occupy
4 will occupy
e. Next argument
3 will be in the place of
count, that will be returned.
So she exposed a macro that accepts variable number of arguments as the API requested. This macro internally used the
COUNTX macro to get number of arguments passed. And she passed the
count and variable arguments to the actual
C program using this hack.
And its output.