Search code examples
cvariadic-functions

number of passed arguments in a va_list


All,

I want to control the number of passed parameters in a va_list.

va_list args;
va_start(args, fmts);
        vfprintf(stdout, fmts, args);
va_end(args);

Is there any possibility to get the number of parameters just after a va_start?


Solution

  • Not exactly what you want, but you can use this macro to count params

    #include <stdio.h>
    #include <stdarg.h>
    
    #define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
    #define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    
    #define fn(...) fn(NARGS(__VA_ARGS__) - 1, __VA_ARGS__)
    
    static void (fn)(int n, const char *fmt, ...)
    {
        va_list args;
    
        va_start(args, fmt);
        printf("%d params received\n", n);
        vprintf(fmt, args);
        va_end(args);
    }
    
    int main(void)
    {
        fn("%s %d %f\n", "Hello", 7, 5.1);
        return 0;
    }