Variadic macro to count number of arguments
July 17th, 2010 § 20 Comments
The C-Preprocessor is a very powerful mechanism, which offers many different features. One of these features is called Variadic macros: macros that accept a varying number of arguments. It is interesting to note at this point, that such Variadic macros, despite being part of the C99 Standard, are not part of the C++ Standard at the moment. However, a big number of C++ compilers support it nevertheless.
While allowing the definition of Variadic macros, there is no built-in (preprocessor) way of obtaining the actual number of arguments that is passed to a specific Variadic macro. In this post we shall provide a possible macro implementation for such a query.
Let us first present the solution (which has also been proposed before), and then we shall move on to discuss how it works and its limitations;
#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(__VA_ARGS__, 5,4,3,2,1) #define VA_NUM_ARGS_IMPL(_1,_2,_3,_4,_5,N,...) N // to verify, run the preprocessor alone (g++ -E): VA_NUM_ARGS(x,y,z)
As with every Variadic macro, __VA_ARGS__ is replaced with the passed arguments, therefore making a little “shift” in the arguments following it. Thus, when we check the arguments being passed to VA_NUM_ARGS_IMPL, the aforementioned “shift” causes the sixth argument to hold the right – initial – number of arguments.
The given implementation imposes a couple of limitations:
- It will not work correctly for zero arguments. Some suggestions for an implementation capable of supporting this feature can be found in the comments section below.
- It supports only a limited number of arguments (up to 5, to be precise). The macro can be extended to support a maximal number of up to 63 arguments (in a way that is pretty obvious), which seems to push the upper bound for number of preprocessor macro arguments any way.
Can you propose a case where this would be useful? I am planning to share a number of ideas in future posts.