Search code examples
cconditional-operator

Use of brackets in expression that include ternary operator


Possible Duplicate:
Error: lvalue required in this simple C code? (Ternary with assignment?)

In the following piece of code I got an error like "lvalue required as left operand of assignment". I am unable to understand why such an error is being reported. But when I am using parenthesis in the expression like (i>j)?(k=i):(k=j) it is not reporting an error. please explain.

int main() {
    int i = 2;
    int j = 9;
    int k;

    (i > j) ? k = i : k = j;
    printf("%d\n", k);

    return 0;
}

Solution

  • It's clear that this condition can be rewritten in a better way, but your problem is observed because of the precedence of = and ?: operators.

    The assignment operator ?: has higher precedence than =, thus the expression

    ( i > j ) ? k = i : k = j;
    

    Is equivalent to

    (( i > j ) ? k = i : k) = j;
    

    Which is not correct, because you cannot assign to an expression result.

    In fact, this case is similar to (( i > j ) : i : j) = 10; which isn't correct either.