Use of brackets in expression that include ternary

2019-08-08 23:09发布

问题:

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;
}

回答1:

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.



回答2:

Without your extra ()s, I think the operator precedence is grouping it as

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

Which obviously isn't what you want and does have lvalue issues.

Fix it with

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



回答3:

How about writing like this.

int main()
 {
   int i,j,k;
   i=2;j=9;
   k = (i > j) ? i : j;
   printf("%d\n",k);
   return 0;
 }


回答4:

Rather :

k = i > j ? i : j;


回答5:

You need to assign the return value of this operator . The syntax for ternary operator is following..

result = condition ? first_expression : second_expression;  

that you missing in your code.. So you can simply put it like following..

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