Abstracting operators by booleans


Lets say I have a boolean bool, and two ints a and b. If bool is true, I want to return a < b, and if bool is false I want to return a > b. Obviously I can write:

if (bool)
    return a < b;
    return a > b;

But this is repetitive. I only want to have to write one return statement, of the form return a (desired operator) b, but I am not sure what that would look like. What would be the simplest way to do this? Obviously this example is fairly trivial, but for larger blocks of code, I’d prefer to not have to rewrite it multiple times with only the operator changed.

>Solution :

In my opinion there’s no such operator in C, plus, C doesn’t have operator overloading, so that’s not possible too.

The best you can do is a function to encapsulate this logic:

function findWhetherLessOrMore(bool findWhetherLess, int operand1, int operand2) {
    return findWhetherLess ? operand1 < operand2 : operand1 > operand2;

Leave a ReplyCancel reply