Michocio
Michocio

Reputation: 523

Comparator as function parameter

Is there any possibility in C89 to pass an operator as function parameter? I mean pass for expample <, ==, >= etc. Something like custom comparator in Java, but passed only with particular symbol. Maybe there is solution with special kind of preprocessor macro (I try to use '#' taken from processor macros)?

I know about pointers to functions, but I want something a little bit different.


Example:

void fun(int a, int b, comperator)
{
    if(a comperator b)
        ........
}

Upvotes: 1

Views: 216

Answers (3)

technosaurus
technosaurus

Reputation: 7802

The easiest way would be to use enums that represent the comparators but with some manipulation you could write a macro wrapper to fun() that calls funLT(), funGT... or enumerates the comparators to LT,GT,.. for use in a switch case.

If fun(...) is rather large you probably want to use enums and a switch case inside the function at the appropriate location.

enum{LT,GT,EQ,NE,LE,GE};

#define fun(a,b,OP) fun_(a,b, 
   (0 OP 1) \
      ? (1 OP 0) \
         ? NE \
         : (0 OP 0) \
            ? LE \
            : LT \
      : (0 OP 0) \
         ? (1 OP 0) \
            ? GE \
            : EQ \
         : GT \
    )

fun(int a, int b, int op){
//code
  switch(op){
  case GE: //etc...
  }
//more code
}

If the function is small you may instead prefer to have separate functions for each operator

#define fun(a,b,OP) \ 
   (0 OP 1) \
      ? (1 OP 0) \
         ? funNE((a),(b)) \
         : (0 OP 0) \
            ? funLE((a),(b)) \
            : funLT((a),(b)) \
      : (0 OP 0) \
         ? (1 OP 0) \
            ? funGE((a),(b)) \
            : funEQ((a),(b)) \
         : funGT((a),(b))

Upvotes: 0

anatolyg
anatolyg

Reputation: 28241

You can use a macro. But remember - a macro is not a function; it has different (ugly) syntax, some specific problems, some advantages, etc.

Suppose you have a function:

int fun(int x, int y)
{
    if (x < y)
        return 1;
    else if (x < 2 * y)
        return 2;
    else if (x < 2 * y)
        return 3;
    else
        return 4;
}

To use a different comparator, first convert it to a macro:

#define FUN(x, y) \
x < y ? 1 : \
x < 2 * y ? 2 : \
x < 3 * y ? 3 : \
4

This conversion is very ugly (it will usually by more ugly than in my example), and not always possible, but now you can add a comparator:

#define FUN(x, y, c) \
x c y ? 1 : \
x c 2 * y ? 2 : \
x c 3 * y ? 3 : \
4

Usage:

printf("%d\n", FUN(3, 5, <));

(Note: in macros, you should add parentheses around variables, explained e.g. here; I omitted them for clarity).

Upvotes: 1

cip
cip

Reputation: 79

No You cant , just pass it like a string and make a test in the function

Upvotes: 0

Related Questions