How do I loop through a va_list if the number of additional arguments is unknown?
#include
#include
int add(int x, int y, ...
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()