Variable Number of Parameters

You can use functions with a variable number of parameters. This is found most commonly when writing printf and fprintf libraries.

 

/*
stdarg.h holds the macros and va_list data type needed for variable number of parameters.
*/

#include <stdarg.h>

/*
A function with variable number of parameters requires two things. First, it requires the ellipsis (...), which must be the last parameter of the function. The ellipsis represents the variable argument list. Second, it requires one more variable before the ellipsis (...). Usually you will use this variable as a method for determining how many variables have been pushed onto the ellipsis.

Here is a function that calculates and returns the sum of all variables:
*/

int Sum(int count, ...)
{
   //a pointer to the argument list
   va_list al;

   int x, sum=0;

   //start the argument list
   //count is the first variable before the ellipsis
   va_start(al, count);

   while(count--) {
      //get an int from the list
      x = var_arg(al, int);

      sum += x;
   }

   //stop using the list
   va_end(al);

   return(sum);
}

/*
Some examples of using this new function:
*/

x=Sum(5, 10, 20, 30, 40, 50);
y=Sum(3, a, b, c);