tags:

views:

6471

answers:

3

Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?

Example:

void format_string(char *fmt, ...);

void debug_print(int dbg_lvl, char *fmt, ...) {
    format_string(fmt, /* how do I pass all the arguments from '...'? */);
    fprintf(stdout, fmt);
 }
+19  A: 

To pass the ellipses on, you have to convert them to a va_list and use that va_list in your second function. Specifically;

void format_string(char *fmt,va_list argptr );


void debug_print(int dbg_lvl, char *fmt, ...) 
{    
 va_list argptr;
 va_start(argptr,fmt);
 format_string(fmt, argptr);
 va_end(argptr);
 fprintf(stdout, fmt);
}
Shane MacLaughlin
+9  A: 

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.