Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use default arguments and a variable number of arguments in a single function?

For example, something like this:

#include <cstdarg>

void my_function(int it=42, ...)
{
     /* va_list/start/arg/end code here */
}

What exactly does the above code mean in C++? It compiles fine in G++. Note, I can't imagine any scenario where this would be useful or even what it ought to do. I'm just curious.

like image 292
Alessandro Avatar asked Apr 30 '11 13:04

Alessandro


2 Answers

Yes, there's nothing technically wrong with this function declaration, although I wouldn't recommend this practice because it would be very easy to make a mistake which the compiler couldn't warn about when calling the function.

You can stop providing arguments at the first argument that has a default argument. If you let the default arguments take over then the variable argument list will, of course, be empty.

You can provide arguments beyond the named parameters so populating the variable argument list in which case none of the default arguments will be used.

As you indicate, whether there's a practical situation where this would actual be useful is another question.

like image 41
CB Bailey Avatar answered Oct 14 '22 22:10

CB Bailey


void my_function(int it=42, ...)

You said this function compiles fine with GCC, but you cannot make use of the default argument, you will have to pass argument for the so-called default parameter as well, to work with this function.

my_function("string", 98, 78, 99); //error
my_function(898, "string", 98, 78, 99); //ok, but the param 'it' becomes 898

Ask yourself:

Is the first argument 898 corresponds to the parameter it or it corresponds to the variadic parameter (and you intend to use the default value 42 for it)?

The compiler cannot know your intention!

BTW @Johannes pointed out a good point : you can simply call my_function() without passing any argument. That is the only instance I see when you can make use of the default argument.


Now if you change the position of the default parameter, something like this:

void f(..., int p = 10); //illegal

Then this is illegal in C++ to begin with.

Again, ask yourself : if it was allowed then you could call this as:

f(9879, 97897, 7897);

Is the last argument 7897 corresponds to the parameter p or it corresponds to the variadic parameter (and you intend to use the default value 10 for p)?

The compiler cannot know your intention in this case either.

like image 170
Nawaz Avatar answered Oct 14 '22 21:10

Nawaz