Which disadvantages could I have if I want to use the function
foo(int num, ...)
to implement the variable number of arguments?
I do know the first disadvantage that you can only use one data type.
Is there any way else to do that?
You are not restricted to arguments of one data type; the printf() family of functions in C (and C++) belies that rumour.
The primary disadvantage of the ellipsis notation is that you lose type safety; the compiler cannot tell you when you are using an argument of the wrong type. (The Go programming language allows you to specify that a function takes an arbitrary number of parameters of a single type - which is an interesting idea.)
Inside the function, there must be some way for it to tell how many arguments were provided and what the types are. Referring back to printf() again, the format string tells it what other arguments are expected. Modern compilers know about these format strings and can check that the arguments given match the format string (when the format string is a literal). This allows for some type safety after all - but that won't be available to you. Using a count is one way of handling it - but then you wonder why you aren't using a vector<T> or something similar to pass the data in. Another classic way is to have a marker value - typically a null pointer - at the end of the list of inputs.
So, you often don't need the variadic argument list. When you do use one, you typically leave yourself open to making errors that other mechanisms avoid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With