Reputation: 3005
I am curious about if a logical representation exists for ternary operator that gives the same result for each condition combination. I tried below but it doesn't cover all situations. Is there a correct representation for this problem?
Ternary Condition : a ? b : c
Logical Version : (a && b) || c
Logical version fails in one condition compared to ternary results when the conditions below are given:
(true && true) || true = true
(true && true) || false = true
(true && false) || true = true //must be false
(true && false) || false = false
(false && true) || true = true
(false && true) || false = false
(false && false) || true = true
(false && false) || false = false
Upvotes: 2
Views: 165
Reputation: 13458
If we talk about pre-evaluated boolean variables or constants, a logical equivalent to the ternary operator can be written like Lee commented
(a && b) || (!a && c)
Or alternatively as
(!a || b) && (a || c)
However, since this question is flagged as C#, I think it's important to discuss the case of a
, b
or c
actually being boolean expressions with side effects (like a function call or a property getter with backing logic)
So lets compare the approaches with regard to, how often a
, b
and c
are evaluated:
Case 1: the ternary operator a ? b : c
, a
is evaluated exactly once, and depending on a
, b
or c
is evaluated once.
Case 2: (a && b) || (!a && c)
The number of evaluations of a
for a=1
depend on the value of b
. Note that #a
is the number of evaluations for a
expression.
a b c #a #b #c
0 0 0 2 0 1
0 0 1 2 0 1
0 1 0 2 0 1
0 1 1 2 0 1
1 0 0 2 1 0
1 0 1 2 1 0
1 1 0 1 1 0
1 1 1 1 1 0
Case 3: (!a || b) && (a || c)
again, the number of evaluations of a
for a=1
depend on b
, but in reverse, compared to case 2
a b c #a #b #c
0 0 0 2 0 1
0 0 1 2 0 1
0 1 0 2 0 1
0 1 1 2 0 1
1 0 0 1 1 0
1 0 1 1 1 0
1 1 0 2 1 0
1 1 1 2 1 0
I don't consider the expression evaluation side effect, where the evaluation of a
changes the value of subsequent evaluations, since it would probably be off topic.
Upvotes: 1