英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论