25

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

2
  • 1
    You mean a variadic function? Like printf? Have you looked up <varargs.h>? Commented Apr 9, 2012 at 9:16
  • 1
    possible duplicate of passing variable number of arguments Commented Apr 9, 2012 at 9:26

1 Answer 1

42

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

Sign up to request clarification or add additional context in comments.

1 Comment

Kinda old question but I saw in a Cuda C example inside the main function something like int N = ...; What does this mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.