The Conditional Operator

The conditional operator is an operator used in C and C++ (as well as other languages, such as C#). The ?: operator returns one of two values depending on the result of an expression.

The Code:

New Project105.png

The Output of Your Code:

New Project106.png

The code above checks the value of the age variable and displays the corresponding message to the screen.
This can be done in a more elegant and shorter way by using the ?: operator, which has the following form:

Exp1 ? Exp2 : Exp3;

The ?: operator works the following way: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
So, the example above can be replaced by the following:

The Code:

New Project107

The Output of Your Program:

New Project106

Prev Lesson:                     Next Lesson:

Logical Operators         Introduction of Methods