# Ternary Operator to choose which operator to use

• 06-26-2011
cncool
Ternary Operator to choose which operator to use
Is there a way to use the ternary operator to choose between two operators?

Example:

Code:

```BOOL greaterThan = true; int x = 5; int y = 10; if(x (greaterThan? > : <) y) {     do something if greaterThan is true, and x > y, or if greaterThan is false, and x < y }```
• 06-26-2011
spaghetticode
You literally spelled out how to do this:

Code:

`if ((greaterThan && x > y) || (!greaterThan && x < y))`
• 06-26-2011
CommonTater
In the expression you don't actually need the greaterThan as factor, unless it relates to some part of your program you aren't showing...

The simplest solution is like this...
Code:

```if (x > y)   { DoThisThing(); }  // x is greater than y else if (y > x)   { DoThatThing(); }  // y is greater than x else   { DoTheOtherThing(); }  // y equals x```
Terniary solutions or those with a single if()-eles statement will let the case of x = y fall right through.
• 06-26-2011
iMalc
The expresions used between the ? and the :, or after the :, must be able to be evaluated on their own.
What you had doesn't work for the same reason that
Code:

`if ( < )`
doesn't work.

This would have worked:
Code:

`if (greaterThan ? x > y : x < y)`
• 06-26-2011
spaghetticode
Quote:

Originally Posted by iMalc
This would have worked:
Code:

`if (greaterThan ? x > y : x < y)`

Judging by what he wrote in plain text I don't think that's actually what he wanted to do... and if it is he'll definitely have to work on putting his ideas into words, because that's fundamental to programming.
• 06-27-2011
iMalc
Quote:

Originally Posted by dennis.cpp
Judging by what he wrote in plain text I don't think that's actually what he wanted to do... and if it is he'll definitely have to work on putting his ideas into words, because that's fundamental to programming.

I'm perplexed as to why you think that.

His statement "do something if greaterThan is true, and x > y, or if greaterThan is false, and x < y" is perfectly understandable, and the expressions you and I wrote are exactly equivalent.
Generate a truth table if you don't believe me. Either your boolean expression rearranging isn't quite second nature yet as it is for me after all these years, or you must misunderstand how the ternary operator works.

Combine the code he actually wrote and the description, and it is 100% clear that he was after exactly what I posted.
• 06-27-2011
spaghetticode
@iMalc - You're perfectly right, my fault. Sorry. :)
• 06-27-2011
nonoob
Not possible to do exacly what OP wanted, but how about
x < y ^ greaterThan
... which flips the logic outcome depending on 'greaterThan'.
There is still the issue of how cases <=, >=, ==, != are handled exactly. But this was not specified to begin with.