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)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes you can do it in C using what are referred to as Variadic Functions.
The standard
printf()andscanf()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:And then you have a special type
va_listwhich gives you the list of arguments passed, and you can use theva_start,va_argandva_endmacros to iterate through the list of arguments.For example:
Example call:
A full example can be found at Wikipedia.
The
countparameter in the example tells the called function how many arguments are passed. Theprintf()andscanf()find that out via the format string, but a simplecountargument can do it too. Sometimes, code uses a sentinel value, such as a negative integer or a null pointer (seeexecl()for example).