Variable-Length Argument in C

The variable-length argument is a feature that allows a function to receive any number of arguments. These are situations where we want a function to handle the 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, the first argument will be always an int, which represents the no .of arguments that we are passing in the 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 the 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 that 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));

Enquire Now

Enquire Now

Enquire Now

Please Sign Up to Download

Please Sign Up to Download

Enquire Now

Please Sign Up to Download

Enquiry Form