Search code examples
cc89

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

Solution

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