How To Pass A Paramter List In C++

This topic is 3540 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I would like to create a function that can pass a parameter list to another function in C++. I tried the following.
void MyFunc(const char *fmt, ...)
{
va_list ap;
va_start(ap,fmt);
printf(fmt, ap); //should just print out what I pass it
va_end(ap);
}

This compiles just fine. I tested with this.
int num =5;
MyFunc("Num is %d\n", num);

I get "Num is 1235752" What is it giving me back? Obviously, my code is wrong. Is there a way to do this correctly? Thanks in advance.

Share on other sites
Hi,

The second parameter in your printf call is wrong. You are using ap, which is of type va_list, which is only used to hold parameter retrieval state and is to be only used as a parameter to va_start, va_arg and va_end calls.

To retrieve the next parameter you have to use va_arg. So that line should correctly read:

printf(fmt, va_arg(ap,int));

Refer to the documentation for additional details - for example here

Share on other sites
I'm pretty convinced that this is only possible by using macros.

Morrandirs suggestion doesn't work if you pass more than one argument, obviously.

Share on other sites
Sorry, I guess it wasn't really a "suggestion". Just the correct version of that specific line.

Share on other sites
Yes, I should have been more clear, what I posted wasn't really a solution to the whole problem, just the correct way to use the va_list family of macros.

Share on other sites
You need to call vprintf rather than printf so the code should be:

void MyFunc(const char *fmt, ...)
{
va_list ap;
va_start(ap,fmt);
vprintf(fmt, ap); //should just print out what I pass it
va_end(ap);
}

Share on other sites
Thanks for all the help. I'll give it a try. Thanks again.

Share on other sites
Quote:
 Original post by fathom88I would like to create a function that can pass a parameter list to another function in C++.

In C++, don't do this. We have a real type system now. It wants to help you avoid making errors that crash your program without telling you anything useful. This kind of offer is hard to refuse.

// Equally as useless as the OP's example ;)#include <iostream>struct MyOutputter {} MyFunc;template <typename T>MyOutputter& operator<<(MyOutputter& out, const T& t) {  std::cout << t;  return out;}

Share on other sites
Quote:
 Original post by Zahlman...

This is known as operator chaining. For printf-like applications, look into boost::format, which brings the advantages of type safety, object safety, and defined behavior to the table. (boost::format accomplishes this by using operator chaining)

Share on other sites

This topic is 3540 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.