It depends. In general, you want the major flow of activity to
be represented in the structure of the code. If the key point
of the algorithm is that the variable x
is initialized, then
the best solution is to use the conditional operator:
x = condition ? f1() : f2();
If the decision is the critical issue for understanding what is
going on, then you'll prefer the if
. In practice, this means
that when both are reasonably possible, you'll use ?:
. The
key being "reasonably"—if you find that you're using the
comma operator in the subexpressions, of the subexpressions have
side effects, then using ?:
is probably not "reasonable".
EDIT:
When you do use the ?:
operator, in all but the simplest
cases, you should format it exactly as you would an if
, e.g.:
x = condition
? complex_expression_1
: complex_expression_2;
I do this regularly. (There's a special case where I'll push
it: if I can reduce the entire function down to a single return
statement. I still won't allow side effects of the comma
operator, but I will sometimes use more complicated expressions
than I otherwise would.)