Functions with variable number of arguments

To access the unnamed, extra arguments you should include the <stdarg.h> include file. To access the additional arguments, you should execute the va_start, then, for each argument, you should execute a va_arg. Note that if you have executed the macro va_start, you should always execute the va_end macro before the function exits. Here is an example that will add any number of integers passed to it. The first integer passed is the number of integers that follow.

 

#include <stdarg.h>

int va_add(int numberOfArgs, ...)

{

va_list ap;

int n = numberOfArgs;

int sum = 0;

va_start(ap,numberOfArgs);

while (n--) {

sum += va_arg(ap,int);

}

va_end(ap);

return sum;

}

We would call this function with

va_add(3,987,876,567);

or

va_add(2,456,789);