Sign in to follow this  
Harryu

C++ functions with variable number of arguments

Recommended Posts

Harryu    174
Sorry about the vague subject, but I didn't really know how to say it. Basically, you know how there are functions like printf, which can take different numbers of arguments, ranging from 2 to (I don't know how many). I was wondering how (if it's possible) could you create a function like this. Thanks, Harry

Share this post


Link to post
Share on other sites
jyk    2094
Here are a couple of relevant links:

-->
-->

For more information, Google 'varargs', 'stdarg', and/or 'cstdarg'.

You might also consider telling us a) whether you're programming in C or C++, and b) why you need a variadic function. Depending on the nature of the problem, someone may be able to recommend a better solution than using C's variable argument list functionality.

Share this post


Link to post
Share on other sites
ToohrVyk    1596
Short answer: you don't. These functions interact badly with types (and, in particular, are not type-safe). The preferred alternative is to use operator chaining to achieve the same effect, because:
  • It's easier to understand and use.
  • There are less pitfalls.
  • It's type-safe.
  • It handles pass-by-reference and temporary values correctly.
  • It's easily extensible.


See boost::format for an example.

Longer answer: variadic functions are a "feature" of the C standard library, parts of which were included in C++ for legacy reasons.

Share this post


Link to post
Share on other sites
Harryu    174
Ok, thanks for both the answers and the links.

To answer the questions, a) C++, b) curiosity.

That's all I really needed, and thanks for telling me it's not good practice to use them before I went off to find some unnecessary use for them in a game or something!

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