The conditional operator is a condensed, limited form of a if
statement. It is condensed in that the decision is limited to a single expression. It is limited because multiple statements cannot be included in the then
or else
clauses. It is sometimes called the ternary operator
due to its three components.
The essential form of the operator is as follows:
LogicalExpression ? ThenExpression : ElseExpression
If the LogicalExpression evaluates to true, then the result of the ThenExpression is returned. Otherwise the result of the ElseExpression is returned.
The following simple example tests to see if a number is less than 10. If it is, 1 is returned, otherwise 2 is returned. The then
and else
expressions in the example are trivial integer literals.
result = (num < 10) ? 1 : 2;
This is equivalent to the following if
statement:
if (num < 10) { result = 1; } else { result = 2; }
Consider the process for calculating overtime. If the employee works 40 hours or less...