C++ functions with variable number of arguments

Started by
2 comments, last by Harryu 16 years, 11 months ago
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
Advertisement
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.
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.
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!

This topic is closed to new replies.

Advertisement