Course Content
Introduction to C++
Ternary Operator
The ternary operator is a shortened version of if...else
, but with a nuance.
It consists of 3 parts:
- Boolean expression;
- Instructions for the
true
case; - Instructions for the
false
case.
Such an operator is convenient to use, for example, when comparing two numbers:
main.cpp
In this case, the result of the ternary operation was written to the result
variable.
If the result of the comparison is true, then the value of the var1
variable will be written to result
.

Conversely, if the comparison result is false, then the value of the var2
variable will be written to the result
variable.

Note
Observe data type compatibility!
How it would look like using if...else
:
main.cpp
What will be written to the result
variable?
Select the correct answer
Section 4.
Chapter 2