24

How can I write (if it's possible at all...) a function which takes an unknown number of parameters in C99 (the return type is constant)?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Z Kim
  • 407
  • 1
  • 3
  • 7

1 Answers1

41

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).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jbx
  • 21,365
  • 18
  • 90
  • 144
  • Kinda old question but I saw in a Cuda C example inside the main function something like `int N = ...;` What does this mean? – mLstudent33 Oct 14 '22 at 01:45