Friday, December 7, 2007

C: Passing on variadic function arguments to another function

I needed to do this today, and it took me a while to google it, so here is complete sample showing how it's done:


// How to pass a variadic argument list to another function
// Justin

#include "iostream"
#include "stdarg.h"

using namespace std;

void debugMessageHelper(char *buffer, const char* format, va_list arglist)
{
vsprintf(buffer, format, arglist);
}

void debugMessage(char *buffer, const char* format, ...)
{
va_list arg;
va_start(arg, format);

debugMessageHelper(buffer, format, arg);

va_end(arg);
}

int main(int argc, char *argv[])
{
char testBuffer[128];

debugMessage(testBuffer, "hello %s %u %-04.2f", "world", 21 33.122f);

cout << "\'" << testBuffer << "\'" << endl;

}


1 comment:

levi said...

That works if your final destination is vsprintf, but what if you're headed for "open" as provided in the fcntl library? Does anyone know if there's a vopen?