Use of brackets in expression that include ternary operator [duplicate]

江枫思渺然 提交于 2019-12-24 07:06:03

问题


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;


来源:https://stackoverflow.com/questions/12068118/use-of-brackets-in-expression-that-include-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!