Conditional Operator in C++
Simple conditional operations can be carried out with the conditional operator (
? :). An expression that makes use of the conditional operator is called a conditional expression. Such an expression can be written in place of the more traditional
if - else statement.
A conditional expression is written in the form:
expression 1 ? expression 2 : expression 3
While evaluating a conditional expression, expression 1 is evaluated first. If expression 1 is true (i.e., if its value is non-zero), then expression 2 is evaluated and this becomes the value of the conditional expression. However, if the expression 1 is false (i.e., if its value is zero) then expression 3 is evaluated and this becomes the value of the conditional expression. Note that only one of the embedded expressions (either expression 2 or expression 3) is evaluated determining the value of a conditional expression.
In the conditional expression below. assume that
a is an integer variable:
(a < 0) ? 0 : 100;
In the above example, the expression
(a < 0) is evaluated first. If it is true, the entire conditional expression takes on the value 0. Otherwise (if the value is not less than 0), the entire conditional expression takes on the value 100.
Precedence of Conditional Operator:
The conditional operator has its own precedence, just above the assignment operators. The associativity is right-to-left.