Function with unknown number of parameters in C

Yes you can do it in C using what are referred to as Variadic Functions.
The standard printf() and scanf() functions do this, for example.

Put the ellipsis (three dots) as the last parameter where you want the ‘variable number of parameters to be.

To access the parameters include the <stdarg.h> header:

#include <stdarg.h>

And then you have a special type va_list which gives you the list of arguments passed, and you can use the va_start, va_arg and va_end macros to iterate through the list of arguments.

For example:

#include <stdarg.h>

int myfunc(int count, ...)
{
   va_list list;
   int j = 0;

   va_start(list, count); 
   for(j=0; j<count; j++)
   {
     printf("%d", va_arg(list, int));
   }

   va_end(list);

   return count;
}

Example call:

myfunc(4, -9, 12, 43, 217);

A full example can be found at Wikipedia.

The count parameter in the example tells the called function how many arguments are passed. The printf() and scanf() find that out via the format string, but a simple count argument can do it too. Sometimes, code uses a sentinel value, such as a negative integer or a null pointer (see
execl()
for example).

Leave a Comment