在包含三元运算符的表达式中使用方括号 [英] Use of brackets in expression that include ternary operator

查看:181
本文介绍了在包含三元运算符的表达式中使用方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


在下面的代码中,我得到了错误,例如 <需要左值作为赋值的左操作数。我不明白为什么要报告这样的错误。但是,当我在(i> j)?(k = i):( k = j)这样的表达式中使用括号时,它没有报告错误。

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

(i> j)? k = i:k = j;
printf(%d\n,k);
返回0;
}


很明显,这种情况可以可以用更好的方式重写,但是由于 = ?:运算符的优先级而引起您的问题。 / p>

赋值运算符?:的优先级高于 = ,因此表达式

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

相当于

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

这是不正确的,因为您不能分配给表达式结果。



实际上,这种情况类似于((i> j):i:j)= 10; 也不正确。


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

解决方案

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.

这篇关于在包含三元运算符的表达式中使用方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆