Pages

Saturday 5 July 2014

C – Variable length argument

  • Variable length arguments is an advanced concept in C language offered by c99 standard. In c89 standard, fixed arguments only can be passed to the functions.
  • When a function gets number of arguments that changes at run time, we can go for variable length arguments.
  • It is denoted as … (3 dots)
  • stdarg.h header file should be included to make use of variable length argument functions.

Example program for variable length arguments in C:

#include <stdio.h>
#include <stdarg.h>

int add(int num,...);

int main()
{
     printf("The value from first function call = " \
            "%d\n", add(2,2,3));
     printf("The value from second function call= " \
            "%d \n", add(4,2,3,4,5));

     /*Note - In function add(2,2,3), 
                   first 2 is total number of arguments
                   2,3 are variable length arguments
              In function add(4,2,3,4,5), 
                   4 is total number of arguments
                   2,3,4,5 are variable length arguments
     */

     return 0;
}

int add(int num,...)
{
     va_list valist;
     int sum = 0;
     int i;

     va_start(valist, num);
     for (i = 0; i < num; i++)
     {
         sum += va_arg(valist, int);
     }
     va_end(valist);
     return sum;
}

Output:

The value from first function call = 5
The value from second function call= 14

       In the above program, function “add” is called twice. But, number of arguments passed to the function gets varies for each. So, 3 dots (…) are mentioned for function ‘add” that indicates that this function will get any number of arguments at run time.

0 comments:

Post a Comment