Is it possible to write a varargs function that sends it argument list to another varargs function?

gct picture gct · Jan 13, 2010 · Viewed 19.3k times · Source

Possible Duplicate:
C Programming: Forward variable argument list.

What I'd like to do is send data to a logging library (that I can't modfify) in a printf kind of way.

So I'd like a function something like this:

void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   sprintf(buff, fmt, <varargs>);
   log(DEBUG, buff);
}

Can I pass varargs to another vararg function in some manner?

Answer

John Dibling picture John Dibling · Jan 13, 2010

You can't forward the variable argument list, since there's no way to express what's underneath the ... as a parameter(s) to another function.

However you can build a va_list from the ... parameters and send that to a function which will format it up properly. This is what vsprintf is for. Example:

void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   va_list args;
   va_start(args, fmt);
   vsprintf(buff, fmt, args);
   va_end(args);
   log(DEBUG, buff);
}