Variable arguments are used by functions in the printf family (printf, fprintf, etc) and others to allow a function to be called with a different number of arguments each time, hence the name varargs.
To implement functions using the variable arguments feature, use #include <stdarg.h>.
Syntax :
int func(int, ... ) {
.
.
.
}
int main() {
func(1, 2, 3);
func(1, 2, 3, 4);
}
stdarg.h header file which provides the functions and macros
va_list valist;
va_start(valist, num);
va_arg(valist, int);
va_end(valist);
Example :
#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));
}
0 Comments