Satish Akula
Satish Akula

Reputation: 75

Passing an operator as an argument to a function in 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.

Upvotes: 5

Views: 4561

Answers (4)

Sepehr Mizanian
Sepehr Mizanian

Reputation: 1

You can write this function by using #define and #. Character #, changes an operator to a string. (for example in #define, #+ = "+").

Sample code:

#include <stdio.h>
#define great(c) ((#c==">")? (1):(0))

int main()
{
    printf ("%d", great(>));
    return 0;
}

In this code, I passed > as a function argument.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

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

Upvotes: 3

MK.
MK.

Reputation: 34527

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));
}

Upvotes: 2

John3136
John3136

Reputation: 29265

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

Upvotes: 2

Related Questions