I want to pass greater than (>) and less than (<) operators as arguments to a function,how is it possible..is there any way to pass those operators as arguments..please any one can help me.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
Yes, it matters. The arguments must be given in the order the function expects them. C passes arguments by value. It has no way of associating a value with an argument other than by position.
You can do terrible things with macros, but in general, no, you can't do this. You typically accept a two argument function and call it, and that function can use >
or <
as appropriate, see the sort
docs for an example.
That said, it's not super efficient (calling a function through a pointer can't be inlined, and for cheap operations like a >
or <
comparison, the function call overhead outweighs the comparison work). Making it efficient requires:
There is no way to pass a 'raw' operator, but there are ways to achieve the same result.
The simplest would be a char
int func(char op, int a, int b)
{
if (op == '<')
{
return a < b;
}
else if (op == '>')
{
return a > b;
}
return -l; /* error */
}
A more complex solution would be to use a function pointer to a function that does the operation (similar to the comparator used by the sort method).
You can create a enum and pass it. Or you can pass in a pointer to a comparison function like this:
#include <stdio.h>
int max(int a, int b, int (*comp)(int, int)) {
if (comp(a, b) < 0) {
return b;
} else {
return a;
}
}
int mycomp(int a, int b) {
return a < b ? -1 : 1;
}
int main() {
printf("%d %d\n", max(1, 2, mycomp), max(2, 1, mycomp));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With