Look up the stdargs mechanism (which comes from C). An example of the usage (assuming the variable arguments are ints, and the last in the list is zero) follows;
Code:
#include <stdarg.h>
void sum(char *msg, ...); /* function prototype */
/* calculate sum of a 0 terminated list */
void sum(char *msg, ...)
{
int total = 0;
va_list ap;
int arg;
va_start(ap, msg); /* Set up so we can access variable argument list */
while ((arg = va_arg(ap,int)) != 0) { /* Loop over the arguments, assuming they are int */
total += arg;
}
printf(msg, total);
va_end(ap); /* Cleanup; necessary before this function returns */
}
int main(void) {
sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0);
return 0;
}
One catch of the stdargs mechanism is that the type of the first argument must be specified, as the first argument is used by the va_start macro to set things up so the rest of the arguments can be accessed. (i.e. it is not possible to have a function of the form SomeFunction(...))
Another catch is that it is not possible to simply get the number of arguments passed or the type of those arguments .... that information must either be known to the program, or some other scheme to recognise the last argument must be used. In the example above, it is assumed that all variable arguments are ints and the last argument given will have a value of zero. In functions like printf(), which use this mechanism, the format string provides information on the arguments that follow it. One serious gotcha is that undefined behaviour results if the function attempts to access more arguments than are passed, or treats any argument as a different type from what it actually is.