Search code examples
cfunctionlogicrational-number

Writing a function to check if a relational statement is true or false


Here is the function (I hope the logic is fairly obvious).

Let x be one of the '<' or '>' operators and a and b are the terms.

int rationalCheck(x, a, b){

    if ( x == '<' && a < b && b < a ){
        printf( "a is less than b\n" );
    }

    if ( x != '>' && a > b && b > a ){
        printf( " a is greater than b\n" );
    }

    return 0;
}

The input into the function would be

(4 < 4) > (3 > 3)

This would evaluate to

(4 < 4) > (3 > 3) is false

Or input into the function would be

(4 < 6) > (2 > 1)

This would evaluate to

(4 < 6) > (2 > 1) is true

Solution

  • You can't pass operators/operations to functions in C. I suggest considering Haskell.

    Alternatively, you can pass operations to macros, so this can be implemented as a macro, hence the definition of the assert macro being something like:

    #include <stdio.h>
    
    #define assert(cond) if (!(cond) && printf("Assertion failed: " # cond " at " __FILE__ ":%d\n", __LINE__) != 0) abort()
    
    int main(void) {
        assert(1 > 1);
    }
    

    Perhaps you want something like:

    #include <stdio.h>
    
    #define rational_check(cond) printf(# cond " is %s\n", (cond) == 0 ? "false" : "true")
    
    int main(void) {
        rational_check((4 > 4) > (3 > 3));
        rational_check((4 < 6) > (2 > 1)); // (4 < 6) > (2 > 1) is 1 > 1, by the way... false
    }
    

    I can't be certain, however, whether this suits your needs. A function pointer can't be derived from rational_check, and it can't work with strings that represent expressions formed during runtime; You'd need to write a translator for any use cases that require those... Otherwise, this should be suitable.