C – Variable length arguments - C-Tutorial

Latest

Monday, 10 October 2016

C – Variable length arguments

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 <stdarg.h>
int add(int num,...);
int main()
{
     printf("\n Result1 = "%d", add(2,2,3));
     printf("\n Result2 = %d ", add(4,2,3,4,5));
}

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;
}

       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.

There are four parts needed for writing variable length arguments:

1. va_list: It is used to declare a variable and also which stores the list of    arguments,

2. va_start: which initializes the list, Which should be placed before processing the variable length arguments

3. va_arg: It is a function which should be written while performing the process. which returns the next argument in the list.


4. va_end: which cleans up the variable argument list

No comments:

Post a Comment