Reputation: 31
I know it's a basic question ,
How can I build\write a function that can receive 3 or 4 arguments ?
Or more general , How can i write a function that can receive unknown number of arguments ?
Thanks !
Upvotes: 1
Views: 139
Reputation: 7434
To define a function with an unknown number of arguments the first one must be known. Then you have to include the stdarg.h
library to access the arguments using it's functions: va_start, va_args, va_en and the type va_list.
In general the function is defined this way. Note that the first argument is not always of type int
. It can be const char *
for more controle on your arguments. for exemple in the printf()
function.
type myFunction(int n, ...)
{
int i;
va_list args;
va_start(args, n);
for (i=0; i<n; i++){
// your argument is va_arg(args, int);
//... do something with your aruments
}
va_end(args);
// return your value
}
check these resources for more about stdarg.h
http://www.cplusplus.com/reference/cstdarg/
or http://en.wikipedia.org/wiki/Stdarg.h
Upvotes: 5
Reputation: 13690
You need a function with a variadic parameter list. Use ellipses to define it:
void foo(int first, ...)
{
}
Use var_args
to parse the parameters. The first parameter is usually used to
Upvotes: 4
Reputation: 401
For the more general aspect, you can store the arguments in an array. And you can then pass a pointer of the array or the array itself to the actual function. This permits you to manipulate those arguments.
Upvotes: 0