4

Possible Duplicate:
C/C++: Passing variable number of arguments around

Imagine I have a function mySuperDuperPrintFunction that takes a variable number of arguments. This function calls printf (or any other function with a variable number of arguments. Can i somehow pass all, or only some, parameters from the arglist to the other function ? Like

void mySuperDuperPrintFunction(char* text, ...) {

    /*
     * Do some cool stuff with the arglist.
     */

    // Call printf with arguments from the arglist
    printf(text, *someWayToExtractTheArglist());
}
Community
  • 1
  • 1
Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • You should look at calling `vprintf` instead. – CB Bailey Nov 08 '11 at 22:22
  • Is this C or C++? In C++ the answer is probably, "don't". In C, you would essentially be looking at some inverse of the `va_arg` unpacking magic. I'm not sure whether the standard provides one at all. – Kerrek SB Nov 08 '11 at 22:24
  • Why is this a duplicate? The OP asks if and how one can *modify* the valist, which is not the same as just passing it on. – Kerrek SB Nov 08 '11 at 22:32

1 Answers1

2

Yes:

va_list args;
va_start(args, text);

vprintf(format_goes_here, args);

You can find info about vprintf here (or check your man pages).

I've done similar for wrapping functions such as write (Unix) and OutputDebugString (Windows) so that I could create a formatted string to pass to them with vsnprintf.

EDIT: I misunderstood your question. No you can't, at least not in C. If you want to pass the variable number of arguments on, the function you're calling must take a va_list argument, just like vprintf does. You can't pass your va_list onto a function such as printf(const char *fmt,...). This link contains more information on the topic.

If the function does take a va_list argument, then you can pass arguments from a specific point (ie. you might to skip the first one). Retrieving arguments with va_arg will update the va_list pointer to the next argument, and then when you pass the va_list to the function (such as vprintf), it'll only be able to retrieve arguments from that point on.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
  • "or any other function with a variable number of arguments" - `vprintf` is not the same, I need to call the function that does actually take the variable number of arguments. Thanks – Niklas R Nov 08 '11 at 22:30
  • @NiklasR oh, I was assuming you wanted a function like `vprintf`. I don't *think* it's possible (at least in C), unless the argument is `va_list`, like with `vprintf`. – AusCBloke Nov 08 '11 at 22:33
  • @NiklasR updated my answer in regards to your question about "...or only some." It still only relates to using a `va_list` though. – AusCBloke Nov 08 '11 at 22:47