Maria: In the fourth line x is incremented for the second time, but the expression x++
returns its old value, the one it had before this second increment. He nce, z will be 11
as well.
Professor: Per fect.
The Conditional Operator
Professor: It’s nice when a computer can undertake some tedious calculations for you,
but it would be even nicer if it could make decisions based on those calculations. For
one thing, that is what computers usu ally do. Even tasks as simple as calculating the
absolute value o f a number involves dec isions whether or not to multiply the number
with minus one. The con ditional operator (?:) allows a program to make decisions
like that. It works with three operands, which makes it a ternary opera tor. Because it is
the only one of its kind, it is sometimes called simply the ternary operator. Although
you will see the cond itional operator written as ?:, it a ctually does not appear quite
like that in code because one of the three operands goes between the symbols ? and :.
With the conditional operator, you write expressions using the following syntax:
condition ? if_true : if_false
The operator works as follows. First, condition is evaluated, and if its value is
true, th en if_true is evaluated and its value is retur ned. However, if condition is
false, then if_false is evaluated and its value is returned. Notice that only one of
the expressions if_true and if_false is actually evaluated as p art of a conditional
operator evaluation.
Basically, this is it. Could you now write an expression that will replace the value of
x with its absolute value?
Mike: condition will probably be some thing like x < 0 because the value should
only change if it is negative. The n, in place of if_true , I would put x *= -1. And
that’s it.
Professor: You’re close but that won’t work, I’m afraid. As for a ny operator, you
must provide all the ne cessary operands for the conditional ope rator as well. If they
are three, then they are three. You sho uld put in something as a third operand even if
there’s nothing to do when condition is f alse. Besides, it is not a common practice
to make assignments within the conditional o perator although it is not wrong. It’s
better to let the operator just return the right value and then assign that value to an
appropriate variable via the assignment operator. The next expression replac es the
value of x with its absolute value:
x = x < 0 ? -x : x
This works because the conditional operator has precedence over the assignment op-
erator, and the less-than operator has precedence over the conditional op erator.
6.5. Operators a nd Expressions 123