1.Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments.
2.Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.
3.Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.
3.Use va_arg macro and va_list variable to access each item in argument list.
4.Use a macro va_end to clean up the memory assigned to va_list variable.
example following:
#include <stdio.h>
#include <stdarg.h>
double average(int num,...) {
va_list valist;
double sum = 0.0;
int i;
va_start(valist, num);
for (i = 0; i < num; i++) {
sum += va_arg(valist, int);
}
va_end(valist);
return sum/num;
}
int main() {
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
void
__syslog(int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
__vsyslog_chk(pri, -1, fmt, ap);
va_end(ap);
}
|