How do I loop through a va_list if the number of additional arguments is unknown?
#include
#include
int add(int x, int y, ...
The two answers above that suggest adding a first argument to indicate the number of arguments miss the point: the number of arguments is unknown.
Using a sentinel value (or series of sentinel values) at the end is the only way to solve the problem.
You probably want to do something like pass the number of arguments as the first parameter.
E.g. see here: http://www.cplusplus.com/reference/clibrary/cstdarg/va_start/
And more discussion here: http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/
Variable arguments can be hazardous so if at all possible I'd try to avoid them. Passing a "vector" type which includes size and a pointer to the element array would be safer.
Use a sentinel value as a terminator, e.g NULL
or -1
You must indicate the number of parameters somehow (if you're writing portable code) when using variable length argument lists. You may be now thinking "But printf doesn't require you to indicate a number of arguments!"
True, however the number can be inferred by first parsing the format strings for % format specifiers.
You use the first argument to indicate the number of elements, and then, you can pass any number of elements to the function.
Here is a typical call:
int i = add(5, 20, 30, 40, 50, 60);
There are 5 numbers to sum, so the first parameter is 5. Then the rest are the 5 numbers to add up.
The function would then be:
int add(int argc, ...)
{
int result = 0;
va_list ptr;
va_start(ptr, argc);
for (int i = 0; i < argc; i++)
{
result += va_arg(ptr, int);
}
return result;
}
References:
va_arg()
va_start()
va_list()