How would I write a function with an undefined number of arguments?
Like, how when using printf(), you write the string in the first argument and in the string use format identifiers. Then, for each format identifier you use is an argument specifying what should be put there in the string.
How can I do this in my own function?
I wrote my own char* concatenating function, and it would be nice if I didn't have to cc(cc(cc(cc(somevalue, another), someothervaule), somethingelse), yetmoredata); if I need to group more than two things together. I know I could re-define the function with two, three, four, five arguments but I would really prefer to do it this way.

Recommended Answers

All 4 Replies

There are three ways to do this:
(a) use the printf style

// Note thist must have at least one fixed argument:
void foo(int flag,...)
 {
    va_list ap;
    va_start(ap, flag);
    if (flag)
      {
         char* s = va_arg(ap, char *);
         double d=va_arg(ap,double);        
         std::cout<<"s == "<<s<<" "<<d<<std::endl; 
        va_end(ap);
       }
   return;
}

Ugly and there are not type-checks until runtime.

Second : get smart. What about how string works and have a function that returns an object of itself ie.

string operator+(const std::string&) const;
//...
string a,b,c,d;
//...
string X=a+b+c+d;

Then there is template land. Now the obvious way to do it is via a typelist or a tuple and since lyou have one class. That says the boost::tuple class is going to be how to go.

Look at:
And never do that, it's a way to nowhere:
- No type check (evidently why) for variadic argument lists.
- No way to check up the end of argument list in called function

I don't have a problem with variable arguments function in limited instances where the function is only called by my program where I can guarentee argument types and end-of-argument-list is checked. For numeric arguments I always indicate end-if-list by -1 argument, or for strings by NULL argument.

If the programmer is not carefull printf() can have unintended bad consequences too (been there and done that).

Yes, I have read these printf-like functions (for job logs and other auxiliary stuff). I never had any troubles with pointers, memory leaks and other C and C++ monsters ;)...

But I'm sure that a variadic parameter list is a bad toy for novices especially when this feature is combined with 2-parameter C-string concatenations. We'll get yet another DaniWeb client with permanently crashed codes ;)...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.