Conditional Operator

The “conditional operator” (? :) is made up of two symbols and requires three expressions. It is similar to an if-else construct. If the first expression evaluates as true, the first operand is assigned the value of the second operand. If the first expression is false, the first operand is assigned the value of the third operand.

The following statement gives the absolute value of the variable val. The vari-able is assigned its original value if it is nonnegative or is negated if its original value is negative:

val = (val >= 0 ) ? val : -val;

The statement is equivalent to the following if-else construct:

if( val >= 0 )

val = val;

else

val = -val;