Examples of conditional expressions
The following expression determines which variable has
the greater value,
y or z, and assigns
the greater value to the variable x: x = (y > z) ? y : z;The following statement is equivalent to
the previous expression.
if (y > z)
x = y;
else
x = z;The following expression calls the function
printf,
which receives the value of the variable c, if c evaluates
to a digit. Otherwise, printf receives the character
constant 'x'. printf(" c = %c\n", isdigit(c) ? c : 'x');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 lower precedence
than the ?: operator in the following expression:
int i,j,k;
(i == 7) ? j ++ : k = j;The compiler will interpret this expression as if it were
parenthesized this way:
int i,j,k;
((i == 7) ? j ++ : k) = j;That is, k is treated as the third operand,
not the entire assignment expression k = j.
To assign the value of
j to k when i
== 7 is false, enclose the last operand in parentheses: int i,j,k;
(i == 7) ? j ++ : (k = j);