为什么三元运算符中出现错误?

huangapple go评论83阅读模式
英文:

Why here error comes in ternary Operator?

问题

The below statement gives an error "unexpected type"

int i = 3;
System.out.println((i == 3) ? i += 3 : i -= 3);

Why does this happen?

英文:

The below statement gives error "unexpected type"

int i = 3;
System.out.println( (i==3) ? i+=3 : i-=3);

why this happens ?

答案1

得分: 8

这是由于运算符优先级+=-= 赋值运算符的优先级低于? : 三元条件表达式运算符。

只有一种方式来解释 i+=3,因为它后面跟着一个 :,即作为三元条件表达式的第一个分支。但 -=3 是模棱两可的,根据优先级进行解析。因为三元条件表达式具有更高的优先级,所以表达式被解析为:

((3==3) ? (i+=3) : i) -= 3

这显然是无意义的,因为你不能赋值给表达式的结果。

如果添加额外的括号以提高赋值的优先级,则可以正常工作:

(3==3) ? (i+=3) : (i-=3)

括号可以省略,但出于可读性的考虑,建议使用(尽管这种情况下很难阅读)。

英文:

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. But the -=3 is ambiguous and resolved according to precedence. 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).

huangapple
  • 本文由 发表于 2020年8月11日 16:03:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63353980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定