[英]Why here error comes in ternary Operator?
The below statement gives error "unexpected type"以下语句给出错误“意外类型”
int i = 3;
System.out.println( (i==3) ? i+=3 : i-=3);
why this happens?为什么会这样?
It's due to operator precedence : the +=
and -=
assignment operators have lower precedence than the ? :
这是由于运算符优先级:
+=
和-=
赋值运算符的优先级低于? :
? :
ternary conditional expression operator. ? :
三元条件表达式运算符。
There is only one way to interpret the i+=3
because it's followed by a :
, namely, as the first branch of the ternary.只有一种解释
i+=3
的方法,因为它后面跟着一个:
,即作为三元的第一个分支。 But the -=3
is ambiguous and resolved according to precedence.但是
-=3
是模棱两可的,并根据优先级解决。 Because the ternary has higher precedence, the expression is parsed like this:因为三元具有更高的优先级,所以表达式解析如下:
((3==3) ? (i+=3) : i) -= 3
which is obviously nonsense, because you cannot assign to the result of an expression.这显然是无稽之谈,因为您不能分配给表达式的结果。
It works if you add extra parentheses to make the assignments take precedence:如果您添加额外的括号以使分配优先,它会起作用:
(3==3) ? (i+=3) : (i-=3)
The parentheses around i+=3
are optional but recommended for readability (insofar as this thing is ever going to be readable). i+=3
周围的括号是可选的,但为了可读性而推荐(只要这个东西永远是可读的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.