Wednesday, 12 November 2014

Passing Variable number of Arguments in C

Sometimes the input to the function is not fixed. Total number of arguments to the function is not same.

In such scenarios, we can use concept called variable arguments which allows us to define the functions that take variable number of arguments. In below example, we have used sum function which takes different number of arguments and of different types.

Please note that while calling the function, we have used first parameter to specify the total number of arguments to be passed.

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

double sum(int num,...);

int main()
   printf("Sum of 2.0, 3, 4, 5 = %f\n", sum(4, 2.0,3,4,5));
   printf("Sum of 5.5, 10, 11,22,15 = %f\n", sum(5, 5.5,10,11,22,15));
double sum(int num,...)
    va_list valist;
    double rsum = 0.0;
    int i;
    va_start(valist, num);
    for (i = 0; i < num; i++)
      if (i==0)  
               //first argument will be double type.   
         rsum += va_arg(valist, double);
              //arguments will be int type except first param.
               rsum += va_arg(valist, int);
//release the memory of valist
    return rsum;

Sponsored Links

Popular Posts



Google+ Followers

Google+ Badge