Selections in C++: Conditional Expressions

A conditional expression evaluates an expression based on a condition.

You might want to assign a variable a value that is restricted by certain conditions. For exam­ple, the following statement assigns 1 to y if x is greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0)

y = 1;


y = -1;

Alternatively, as in the next example, you can use a conditional expression to achieve the same result:

y = x > 0 ? 1 : -1;

Conditional expressions have a completely different structure and do not include an explicit if. The syntax is shown here:

boolean-expression ? expressionl : expression2;

The result of this conditional expression is expression1 if boolean-expression is true; otherwise, the result is expression2.

Suppose you want to assign the larger number between variable num1 and num2 to max. You can simply write a statement using the conditional expression:

max = num1 > num2 ? num1 : num2;

As another example, the following statement displays the message “num is even” if num is even, and otherwise displays “num is odd.”

cout << (num % 2 == 0 ? “num is even” : “num is odd”) << endl;

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *