Reputation: 23
I have a function that accepts 3 parameters, however I also want it to only accept the first two and not care about the third. How can I do this in C. I tried just declaring the function in the header file as void list()
thinking this might imply that we don't care how many parameters but this didn't work.
void list(uint8_t _pin, unsigned int time, unsigned long tasks)
Upvotes: 0
Views: 123
Reputation: 59
A different solution to your problem without variable parameters is to do something like this:
void list(int argc, char **argv);
You have two parameters always, however what changes is the contents of argv and the count of what is inside it. You might have seen this in the entry point (main function) of other C programs. The parameters argc, argument count, and argv, argument vector, give the number and values of what you need.
Then inside list you could do something like:
if (argc == 2)
do_something;
else if(argc == 3)
do_something_else;
else
whatever;
Upvotes: 0
Reputation: 15844
Here is a trick explained in SO here : C default arguments. You can make third parameter as default in function declaration as follows:
typedef struct {
uint8_t _pin;
unsigned int time;
unsigned long tasks;
} f_args;
double var_f(f_args in){
uint8_t _pin = in._pin? in._pin : 8;
unsigned int time = in.time ? in.time : 3;
unsigned long tasks =in.tasks? in.taska : 0;
return f_base(i_out, x_out);
return list(_pin, time, tasks);
}
#define list(...) var_f((f_args){__VA_ARGS__});
So you can call your function as follows:
list(2,5);
Upvotes: 0
Reputation: 134396
What you want is called Variadic function. It can accept variable number of arguments.
**Famous examples: printf()
/scanf()
These functions contain an ellipsis (…
) notation in the argument list, and uses special macros to access the variable arguments.
The most basic idea is to write a function that accepts a variable number of arguments. So, it must be declared with a prototype that says so.
The syntax of ISO C requires at least one fixed argument before the …
. thus, we write the fixed arguments as usual, and then add the …
notain at the end of the parameter list to indicate the possibility of additional arguments. For example,
int func (const char *a, int b, …)
{
…
}
defines a function func()
which returns an int
and takes two required arguments, a const char *
and an int
. These are followed by any number of anonymous arguments.
You can check the On-line GNU manual for more details.
Upvotes: 3