Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
else
    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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading