Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

Function with unknown number of parameters in C

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...