Does anyone knows how I might be able to implement variable arity for functions in C?
For example, a summing function:
Sum(1,2,3,4...); (Takes in a variable number of args)
Thanks!
Does anyone knows how I might be able to implement variable arity for functions in C?
For example, a summing function:
Sum(1,2,3,4...); (Takes in a variable number of args)
Thanks!
A variable parameter list of ints. Adjust type as necessary:
#include <stdarg.h>
void myfunc(int firstarg, ...)
{
va_list v;
int i = firstarg;
va_start(v, firstarg);
while(i != -1)
{
// do things
i = va_arg(v, int);
}
va_end(v);
}
You must be able to determine when to stop reading the variable args. This is done with a terminator argument (-1 in my example), or by knowing the expected number of args from some other source (for example, by examining a formatting string as in printf).
If you're trying to implement variable arity functions look at http://www.cprogramming.com/tutorial/lesson17.html for an introduction.
If all aditional arguments are of the same type, you could also pass an array instead of using variadic macros.
With C99 compound literals and some macro magic, this can look quite nice:
#include <stdio.h>
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
int _sum(size_t count, int values[])
{
int s = 0;
while(count--) s += values[count];
return s;
}
int main(void)
{
printf("%i", sum(1, 2, 3));
}