- [Instructor] The ternary conditional operator
is a simple shortcut for choosing a value
based on a condition.
This is working.cpp from Chapter Four of the exercise files.
And I'll start by declaring couple of variables,
int x and int y,
and then we'll compare them.
We'll see if x is greater than y,
and we'll return either a yes or a no,
based on that condition.
And we're going to use the
ternary conditional operator for this.
So our result is going to be a string,
so we'll declare a constant character pointer, call it s,
equals, if x is greater than y ? "yes" : "no"
so it's really quite simple.
If the condition is true,
then the ternary operator will return its second operand,
the first operand being the condition.
And otherwise it will return the last operand.
So the two results are separated by a colon,
and the condition is separated by the question mark.
So we'll go ahead and print our result,
we'll put it in this puts here,
and we'll build and run, and it says no,
x is not greater than y.
And if we change this to less than, we'll get yes.
So the ternary conditional operator is quite simple.
It has three operands.
The first operand is the condition.
The second operand is returned if the condition is true.
And the final operand is returned if the condition is false.
This can be very handy in cases
where you just need to select a single value
and don't need the complexity
of a block oriented if/else construct.
The ternary conditional operator
is a common shortcut for testing a simple condition
with a simple result.
It looks a little weird if you've not seen it before,
but it's actually quite simple and quite common.