Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
Aymanadou Avatar asked Oct 14 '25 04:10

Aymanadou


2 Answers

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;
}
like image 99
David Ranieri Avatar answered Oct 16 '25 20:10

David Ranieri


You can not count them directly.

For example printf is a variable count function which uses its first parameter to count the following arguments:

printf("%s %i %d", ...);

Function printf first parses its first argument ("%s %i %d") and then estimates there are 3 more arguments.

In your case, you have to parse fmts ans extract %-specifiers then estimate other arguments. Actually each %[flags][width][.precision][length]specifier could count as an argument. read more...

like image 43
masoud Avatar answered Oct 16 '25 21:10

masoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!