C++ preprocessor __VA_ARGS__ number of arguments C++ preprocessor __VA_ARGS__ number of arguments c c

C++ preprocessor __VA_ARGS__ number of arguments


I usually use this macro to find a number of params:

#define NUMARGS(...)  (sizeof((int[]){__VA_ARGS__})/sizeof(int))

Full example:

#include <stdio.h>#include <string.h>#include <stdarg.h>#define NUMARGS(...)  (sizeof((int[]){__VA_ARGS__})/sizeof(int))#define SUM(...)  (sum(NUMARGS(__VA_ARGS__), __VA_ARGS__))void sum(int numargs, ...);int main(int argc, char *argv[]) {    SUM(1);    SUM(1, 2);    SUM(1, 2, 3);    SUM(1, 2, 3, 4);    return 1;}void sum(int numargs, ...) {    int     total = 0;    va_list ap;    printf("sum() called with %d params:", numargs);    va_start(ap, numargs);    while (numargs--)        total += va_arg(ap, int);    va_end(ap);    printf(" %d\n", total);    return;}

It is completely valid C99 code. It has one drawback, though - you cannot invoke the macro SUM() without params, but GCC has a solution to it - see here.

So in case of GCC you need to define macros like this:

#define       NUMARGS(...)  (sizeof((int[]){0, ##__VA_ARGS__})/sizeof(int)-1)#define       SUM(...)  sum(NUMARGS(__VA_ARGS__), ##__VA_ARGS__)

and it will work even with empty parameter list


This is actually compiler dependent, and not supported by any standard.

Here however you have a macro implementation that does the count:

#define PP_NARG(...) \         PP_NARG_(__VA_ARGS__,PP_RSEQ_N())#define PP_NARG_(...) \         PP_ARG_N(__VA_ARGS__)#define PP_ARG_N( \          _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \         _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \         _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \         _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \         _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \         _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \         _61,_62,_63,N,...) N#define PP_RSEQ_N() \         63,62,61,60,                   \         59,58,57,56,55,54,53,52,51,50, \         49,48,47,46,45,44,43,42,41,40, \         39,38,37,36,35,34,33,32,31,30, \         29,28,27,26,25,24,23,22,21,20, \         19,18,17,16,15,14,13,12,11,10, \         9,8,7,6,5,4,3,2,1,0/* Some test cases */PP_NARG(A) -> 1PP_NARG(A,B) -> 2PP_NARG(A,B,C) -> 3PP_NARG(A,B,C,D) -> 4PP_NARG(A,B,C,D,E) -> 5PP_NARG(1,2,3,4,5,6,7,8,9,0,         1,2,3,4,5,6,7,8,9,0,         1,2,3,4,5,6,7,8,9,0,         1,2,3,4,5,6,7,8,9,0,         1,2,3,4,5,6,7,8,9,0,         1,2,3,4,5,6,7,8,9,0,         1,2,3) -> 63


If you are using C++11, and you need the value as a C++ compile-time constant, a very elegant solution is this:

#include <tuple>#define MACRO(...) \    std::cout << "num args: " \    << std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value \    << std::endl;

Please note: the counting happens entirely at compile time, and the value can be used whenever compile-time integer is required, for instance as a template parameter to std::array.