I think I’m going to have to defend the instructors here. I’ve never taken a C++ course, but I have taken courses in C, Java, and JavaScript before. In each of them, the ternary operator were taught fairly early on. Typically, they are taught immediately after if
and else
are taught, and before loops are taught.
You don’t have to use them but they are good to know about in case you encounter them in other code. Programming languages can often express the same in multiple ways. Also, sometimes things can be subtlety different, and the ternary operator is actually one of those cases.
I’m going to share an additional thing about the ternary operator that wasn’t covered in the course, and I hope that this might be something that is helpful and that you can learn from (and not just cause further confusion).
A big difference between the ternary and an if
/ else
block is that if
/ else
are statements and don’t return anything, but the ternary operator does return a value. So, while you can use it in place of if
/ else
, you can also use it directly provide a result for another expression, a return, or an assignment.
An example of this would be the original line:
direction.x < 0.f ? rightLeft = -1.f : rightLeft = 1.f;
That isn’t much difference than using if/else
. But you could instead write it like this:
rightLeft = direction.x < 0.f ? -1.f : 1.f;
In that case, the condition of direction.x < 0.f
is evaluated, and then a value of -1f
or 1f
is returned, which then is assigned to rightLeft
.
Or hypothetically, if we had a function that determined the facing by passing in the direction.x as “x
”, that function could have something like:
return x < 0.f ? -1.f : 1.f
You could write those with if/else
blocks too, but I hope this helps show the value of the operator. With practice, ternary can be actually easier to read than if/else
blocks.