Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an operator as an argument to a function in C

Tags:

c

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.

like image 736
Satish Akula Avatar asked Jan 19 '17 05:01

Satish Akula


People also ask

Can we pass a function as an argument to a function?

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.

Does the order matter when passing arguments to a function?

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.


3 Answers

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:

  1. Multiple copies of the code, one for each possible operator (possibly generated via macros)
  2. Moving to C++ and using templated code with functors/lambdas that can be inlined properly
like image 143
ShadowRanger Avatar answered Oct 08 '22 18:10

ShadowRanger


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

like image 26
John3136 Avatar answered Oct 08 '22 18:10

John3136


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));
}
like image 32
MK. Avatar answered Oct 08 '22 19:10

MK.