course content

Course Content

Introduction to C++

Ternary OperatorTernary Operator

The ternary operator is a shortened version of if...else, but with a nuance. It consists of 3 parts:

  1. Boolean expression;
  2. Instructions for the true case;
  3. Instructions for the false case.

Such an operator is convenient to use, for example, when comparing two numbers:

cpp

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:

cpp

main.cpp

question-icon

What will be written to the result variable?

Select the correct answer

Section 4.

Chapter 2