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());
}
3
  • You should look at calling vprintf instead. Commented Nov 8, 2011 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. Commented Nov 8, 2011 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. Commented Nov 8, 2011 at 22:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"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
@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.
@NiklasR updated my answer in regards to your question about "...or only some." It still only relates to using a va_list though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.