Friday, July 29, 2016

C Basics - Variable Arguments in C

C allows o define a function which can accept variable number of parameters. The following example shows the definition of such a function.

#include <stdarg.h>
int sum(int, ... ) {
   statements;
}

int main() {
   sum(2, 6, 7);
   sum(4, 3, 5, 7, 9);
   return 0;
}

In function sum(int, ... ), the first parameter is always an int which will represent the total number variable arguments passed. The second parameter is three dotes (...) which represents the variable number of arguments.

stdarg.h header file provides the functions and macros to implement the functionality of variable arguments.

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

int sum(int argc,...) {

   va_list valist;
   int sum = 0;
   int i;

   /* initialize valist for num number of arguments */
   va_start(valist, argc);

   /* access all the arguments assigned to valist */
   for (i = 0; i < argc; i++) {
      sum += va_arg(valist, int);
   }
 
   /* clean memory reserved for valist */
   va_end(valist);

   return sum;
}

int main() {
   printf("Sum of 2, 3, 4, 5 = %d\n", sum(4, 2,3,4,5));
   printf("Sum of 5, 10, 15 = %d\n", sum(3, 5,10,15));
   return 0;
}
Output of above program,

Sum of 2, 3, 4, 5 = 14
Sum of 5, 10, 15 = 30 

In the above function, valist is a variable of type va_list. This type is defined in stdarg.h header file. va_start macro is used to initialize the va_list variable to an argument list. va_arg macro is used to access each item in argument list. va_end macro is used to clean up the memory assigned to va_list variable.



Related topics:
Functions in C   |   Function Definition and Declaration in C   |   Calling a Function in C   |   Recursion in C   |   Command Line Arguments in C

List of topics: C Programming

No comments:

Post a Comment