Search code examples
c++variadic-functions

varargs to printf all arguments


if I have this function:

printAll(const char *message, ...)
{
    va_list argptr = NULL;
    va_start(argptr, message);
   
    // todo: how to printf all the arguments in the message?   
 
    va_end(argptr);    
}

Suppose I call the function like this:

printAll("My info: Value1 = %d, Value 2=%d", 1, 2);

In this line: // todo: how to printf all the arguments in the message?

How can I print them all in order to have:

My info: Value1 = 1, Value 2=2

Solution

  • You're looking for the vprintf() function which was designed to do exactly this:

    vprintf(message, argptr);
    

    The v*printf() family of functions work basically in the same way as their normal counterparts, except they take a va_list instead of varargs. They don't call va_end() for you, so the way you have it now is correct.