Sign in to follow this  
fathom88

How To Pass A Paramter List In C++

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by fathom88
I 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 this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this