Give variable parameter list to a called function in C

Viewed 57

I have a function with a printf-like variable parameter list that I call for example with:

debugMsg(__FILE__, __LINE__, "failed with var %s = %d\n", var, val);

Now I need a wrapper function for this, e.g.:

void debugMsgWrapper(const char* FileName, int LineNo, const char* FmtStr, ...)
{
    // do some other things
    DebugMsg(FileName, LineNo, FmtStr, ...);
}

Of course this doesn't work with the parameter list specified as ... but I don't have any idea how to copy the parameter list to the called function. I had a look at
void va_copy(va_list dest, va_list src);
but could not find how to use it.

How can I give the variable parameter list to the called function?

1 Answers

You need to re-write debugMsg so that it takes a va_list instead of a variable number of arguments. Here's how you'd do it:

void
debugMsg(const char *FileName, int LineNo, const char *FmtStr, va_list args);

void
debugMsgWrapper(const char *FileName, int LineNo, const char *FmtStr, ...)
{
    va_list args;

    // do some other things
    va_start(args, FmtStr); // Make args start after FmtStr;
    debugMsg(FileName, LineNo, FmtStr, args);
    va_end(args);
}

You can then, in debugMsg, repeatedly pull arguments from args via va_arg:

int n;
const char *string;

n = va_arg(args, int);
string = va_args(args, char*);
Related