Conditional Expressions:
The statements
if (a > b)
z = a;
else
z = b;
compute in z the maximum of a and b. The conditional expression, written with the ternary operator " ?: " , provides an alternate way to write this and similar constructions . In the expressions
expr1 ? expr2 : expr3
the expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2 is evaluated, and that is the value of the conditional expression Otherswise expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. Thus to set Z to the maximum of a and b,
z = (a > b) ? a : b; /* z = max ( a, b); */
The binding of operators in C and C++ is specified (in the corresponding Standards) by a factored language grammar, rather than a precedence table. This creates some subtle conflicts. For example, in C, the syntax for a conditional expression is:
logical-OR-expression ? expression : conditional-expression
while in C++ it is:
logical-or-expression ? expression : assignment-expression
Hence, the expression:
e = a ? b : c = d
is parsed differently in the two languages. In C, this expression is parsed as:
e = ((a ? b : c) = d)
which is a semantic error, since the result of a conditional-expression is not an lvalue. In C++, it is parsed as:
e = (a ? b : (c = d))
The following is an equivalent expression:
if (y > z) {
x = y;
} else {
x = z;
}
The following expression assigns an integer. If the variable c is less than
zero, output receives the value of c. If not, output receives the return code
from the search function.
c = c<0?c:search("hello");
If the last operand of a conditional expression contains an assignment
operator, use parentheses to ensure the expression evaluates properly. For
example, the = operator has higher precedence than the ?: operator in the
following expression:
(i == 7) ? j ++ : k = j;