Andrew Simpson
Andrew Simpson

Reputation: 7334

How to use multiple nested ternary operators to return a value

I am looking at using a multiple nested ternary operators. I have 3 values I want to compare. All 3 are integers. For example:

val1
val2
threshold

From all this I want a result of 1 or 0.

So, if I was to do this using if-else statements, my logic will look like this:

if (val1 - val2 > threshold)
{
    result = 1;
}
else if (val2 - val1 > threshold)
{
    result = 1;
}

So far I have this:

int d = (alpha < 0 ? -alpha : alpha) > threshold ? (alpha < 0 ? -alpha : alpha) : 1;

which, although it compiles, does not give me the same result...

Upvotes: 1

Views: 5002

Answers (3)

Chris Mantle
Chris Mantle

Reputation: 6693

Why not this:

int d = (val1 - val2 > threshold) || (val2 - val1 > threshold) ? 1 : 0;

However, consider carefully if this is more readable than the if statements. Indescriminate use of the ?: operator can make it more difficult to read and comprehend code.

Upvotes: 1

David Pilkington
David Pilkington

Reputation: 13628

result = val1 - val2 > threshold ? 1 : val2 - val1 > threshold ? 1 : 0

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

result = (val1 - val2 > thresold) ? 1 : (val2-val1 > thresold) ? 1 : 0;

Or

result = (val1 - val2 > thresold) || (val2-val1 > thresold) ? 1 : 0;

Or

result = Math.Abs(val1 - val2) > thresold ? 1 : 0;

Upvotes: 6

Related Questions