How to write a function that takes variable number of arguments in C
The C language supports function that takes variable number of arguments using standard argument interface (stdarg.h). The following are the functions used to handle variable number of arguments in a function.
#include <stdarg.h> void va_start(va_list ap, last); type va_arg(va_list ap, type); void va_end(va_list ap); void va_copy(va_list dest, va_list src);
The prototype of a function which takes varying number of arguments will be similar to the following.
int max_of(int count,int num1,...);
It is declared similar to any other function but a “…” is followed by fixed arguments representing the start of variable number of arguments. The varying number of arguments supplied to such function can be of any data type. Basically va_start() is used to specify the beginning of first varying argument, va_arg() is used to extract all arguments and vs_end() is used to specify the end of accessing arguments. Each call to va_start() must be matched with a call to va_end().
In the following example, we will compute the maximum value of all the variable number of integers supplied to the function. The first argument specifies the number of integers supplied.
[neo@techpulp ~]# cat vargs.c
#include <stdio.h>
#include <stdarg.h>
int max_of(int count,int num1,...)
{
int i, max, val;
va_list ap;
max = num1;
va_start(ap,num1);
for(i=1; i<count; i++) {
val = va_arg(ap,int);
if(val > max) max = val;
}
va_end(ap);
return max;
}
int main(int argc, char *argv[])
{
printf("MAX of 38,10,-10,46 is %d\n",
max_of(4,38,10,-10,46));
printf("MAX of 6,5,4,3,2 is %d\n",
max_of(5,6,5,4,3,2));
return 0;
}
[neo@techpulp ~]#
Let us compile and execute the above C program.
[neo@techpulp ~]# gcc vargs.c -o vargs [neo@techpulp ~]# ./vargs MAX of 38,10,-10,46 is 46 MAX of 6,5,4,3,2 is 6 [neo@techpulp ~]#

