cvariadic-functions

wrapper for a function with variable arguments in C


Recently I wanted to implement a printf wrapper. After some search I found the vprintf is good for this need:

void my_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

But is it possible to implement such a wrapper for printf or any other similar functions with variable arguments instead of va_list?

(I mean, what if they don't provide a v version?)


Since some commenter didn't fully capture my idea, I'd better elaborate it.

Suppose you have a plain printf function as in the C library.

Some one gives you a fmt string "%d %u %f", and corresponding inputs.

Now you want to write a function similar to printf, but with all %f replaced by %.2f.

Of course you can use two statements to finish the task:

replace(fmt, "%f", "%.2f");
printf(fmt, inputs);

But if you use this function many times, probably you want to have a wrapper to save some time.

A macro can finish this task, of course. But is it possible without a macro, like:

void myprintf(fmt, ...)
{
    replace(fmt, "%f", "%.2f");
    printf(fmt, inputs);
}

The problem here is that you don't know how to feed the inner printf with the arguments ... of myprintf.

Hope this clarifies.


Solution

  • If you just want to use this to prepend an string to the output or so, you could use a variadic macro.

    #define MYPRINT(...) printf("toto has: " __VA_ARGS__)
    

    in that simple example this suppposes that format that you pass in is a string literal, so this is a bit restricted. But I hope you see the pattern how to use such simple macro wrappers.