Variadic funcions can typically only work when you design them in such a way that the type and number of arguments can be deduced by previous arguments. This is usually done in 2 ways:
- The preceding argument contains information on the arguments that are passed. This is the case of printf and the like wherein the format string tells you how many arguments you will get and their types. Additionally, if all the parameters are of the same type, the first argument can be the number of values that are passed.
- The arguments hold a sentinel value at the end. Usually, this type of variadic funcions accept only pointers, with the last argument being NULL.
In the last case, if your compiler supports variadic macros, there are ways to bypass the (very annoying) requirement of having to append NULL for every call:
Code:
void f(void *p, ...) {
va_list arglist;
va_start(arglist, p);
while(p != NULL)
{
/* do something */
p = va_arg(arglist, void*);
}
}
#define F(X, ...) f(X, ## __VA_ARGS__, NULL)
int main()
{
int x, y;
F(&x, &y);
}