Passing variable number of arguments around
To pass the ellipses on, you initialize a va_list
as usual and simply pass it to your second function. You don't use va_arg()
. Specifically;
void format_string(char *fmt,va_list argptr, char *formatted_string);void debug_print(int dbg_lvl, char *fmt, ...) { char formatted_string[MAX_FMT_SIZE]; va_list argptr; va_start(argptr,fmt); format_string(fmt, argptr, formatted_string); va_end(argptr); fprintf(stdout, "%s",formatted_string);}
There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.
The generally used solution is to always provide an alternate form of vararg functions, so printf
has vprintf
which takes a va_list
in place of the ...
. The ...
versions are just wrappers around the va_list
versions.
Variadic Functions can be dangerous. Here's a safer trick:
void func(type* values) { while(*values) { x = *values++; /* do whatever with x */ } }func((type[]){val1,val2,val3,val4,0});