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 and error because it is interpreted as if it were parenthesized this way:
int i, j, k;
((i == 7) ? j ++ : k) = j;
The value k, and not k = j, is treated as the third operand. This error arrises 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 parenetheses. For example:
int i, j, k;
(i == 7) ? j ++ : (k = j);
Operator
Precedence and Associativity
Expressions and
Operators
Types of
Expressions
lvalues
Operator
Precedence and Associativity Table
Conditional
Operator