Gabel Luc
Gabel Luc

Reputation: 19

Variadic function that returns the number of arguments that are passed to it

I tried to implement a function that returns the number of arguments that are passed to it. Here's the code :

int SIZE(int n, ...){

va_list ARGS;
va_start (ARGS, n);
int length(0);

void* current_arg;
do{
    current_arg=va_arg(ARGS, void*);
    length++;
}while( current_arg != nullptr);

va_end(ARGS);
return length;

}

I had done some research prior to this, so I kinda knew it wan't going to work. And indeed it didn't : when I passed two arguments to it, it returned 12 ! I'd still like to understand why it didn't work. I see two options :

I haven't been programming for very long, so I like experimenting with this kind of stuff. Could you help me figure out what is wrong with my function please ? Thanks

Upvotes: 1

Views: 76

Answers (1)

Carl
Carl

Reputation: 2067

Since you tagged C++11 you should consider parameter packs making your function:

template<typename... T>
constexpr unsigned numberOfArguments(const T&... args)
{
    return sizeof...(T);
}

As seen in the comments on the main post, the sizeof...() operator will return the size of the template parameter pack in this case.

Upvotes: 6

Related Questions