Variable Length Argument in C

Variable length argument is feature that allows a function to receive any number of arguments. These are situations where we want a function to handle variable number of arguments according to requirements.

  1. Sum of given numbers.
  2. Minimum of given numbers.

Variable number of arguments are represented by three dotes ( . . .  )

int Fun(int num, . . .)

{

…….

…….

}

int main()

{

            Fun(2,10,20);

            Fun(3,5,6,7);

}

In the above function, when we calling the function the first argument will be always an int  ,it will represent no .of arguments that we are passing in function call. In definition the first formal parameter will access the total no .of argument and followed with three dots( . . ).i.e,ellipses.  To use this functionality always we need to include stdarg.h header file which provides the functions and macros to implement the functionality variable no .of arguments and follow the given steps:

  • 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.
  • Create ava_list type variable in the function definition. This type is defined in stdarg.h header file.
  • 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.
  • Use va_arg macro and va_list variable to access each item in argument list.
  • Use a macro va_end to clean up the memory assigned to va_list 

Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average.

#include<stdio.h>

#include<stdarg.h>

float fun(int num , …)

{

            int i=0;

            float sum=0;

            //creating a va_list type variable

            va_list valist;

            //initialize valist fom num number of arguments

            va_start (valist , num);

            //access all the arguments assigned to valist

            for(;i<num;i++)

                        sum= sum + va_arg(valist,int);

            //cleanup memory reserved for valist

            va_end(valist);

            return sum/num;

}

int main()

{

            printf(“the average of 2,3,4 is = %f\n”, fun(3,2,3,4));

            printf(“the average of 10,20,30,40 is = %f\n”, fun(4,10,20,30,40));

}