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 is an equivalent statement:
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 higher precedence than the ?:
operator in the following expression:
int i,j,k; (i == 7) ? j ++ : k = j;
This expression generates an error because it is interpreted 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. The error arises because a conditional expression is not an lvalue, and the assignment is not valid.
To
make the expression evaluate correctly, enclose the last operand in
parentheses:
int i,j,k; (i == 7) ? j ++ : (k = j);