The expression var1 ? var2 : var3
returns the value of var2
if var1
is considered to have a value equivalent to true
else it returns teh value of var3
.
Note this is not quite the same as:-
if (var1)
varX = var2
else
varX = var3
Since the above construct can not itself appear as part of a larger expression.
In ternery expression, as ? :
is known, one should avoid allowing the component expressions to have side effects other than perhaps the side-effects of ++ or -- operators. For example this isn't a good idea:-
varX = var1 ? doSomethingSignificant() : doSomethingElseSignificant();
In this case it would be better to use the if else
construct. On the hand:-
varX = var1 ? calcSomething(var2) : someOtherCalc(var2);
this is acceptable assuming the called functions don't themselves modify the program state significantly.
Edit:
I think I need to re-enforce this point. Do not use the ternary operator as means to short cut on if
statements. The two have different purposes. If your code is full of ? :
that should be if else
it will be difficult to read. We expect logical flow to appear in if
statements. We expect ? :
when there is a simple logical component to an expression. Note expressions do not modify things only the results of them when assigned should modify things.