Conditional (:?) Operator
C++ language has an extremely powerful and convenient operator which can be used to construct conditional expressions. That is termed as conditional operator. Sometimes, it is also known as ternary operator because it operates on three operands. The: ?Operator takes the form: -
exp1 ? exp2 : exp3
exp1, exp2, exp3 are expressions.
The ternary operator works like this: -
exp1 is evaluated. exp2 is evaluated if it is true and becomes the value of the expression. exp3 is evaluated if exp1 is false and its value becomes the value of the expression.
Example:
x = 10;
y = x > 9? 100: 200;
In the above given example, y will be assigned the value 100. y would have received the value 200 if x had been less than or equal to 9.
The similar code, using the if-else statement is written as: - x =10;
if ( x > 9)
{
y = 100;
}
else
{
y = 200;
}