爪哇。算术运算。标记化。如何?
谁能解释一下或为理解这个例子提供一个很好的参考:
int a=1;
int b=2;
System.out.println(a---b); //correct
System.out.println(a- -b); //correct
System.out.println(a--b); //wrong
谢谢。
Who can explain or give a good reference for understanding this example:
int a=1;
int b=2;
System.out.println(a---b); //correct
System.out.println(a- -b); //correct
System.out.println(a--b); //wrong
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
表达式
a---b
并未(如您所期望的那样)解析为a-(-(-b))
,而是解析为(a-- ) - b
。这个例子说明了这一点:
考虑到这种行为,
a--b
被解析为(a--)b
这显然是一个错误。当您在减号之间放置空格时,
a- -b
它不再被解析为--
运算符,而是解析为二进制和一元减号:a - (-b)
。请注意,您可以编写
a- - -b
,它会被解释为a-(-(-b))
。那么为什么会这样解释呢? @EJP 对另一个答案给出了很好的评论。在 JLS,第 3.2 节中,您可以阅读下列:
The expression
a---b
is not (as you perhaps expected) parsed asa-(-(-b))
but rather as(a--) - b
.This example illustrates it:
With this behaviour in mind,
a--b
is parsed as(a--)b
which is obviously an error.When you put a space between the minuses,
a- -b
it's no longer parsed as the--
operator, but as a binary and unary minus:a - (-b)
.Note that you can write
a- - -b
which is interpreted asa-(-(-b))
.So why is it interpreted like this? Well @EJP gave an excellent comment on another answer. In the JLS, section 3.2 you can read the following:
Java 语言规范。
The Java Language Specification.
-
和--
是一元运算符。因此不能与两个操作数一起使用。这就是为什么是错误的。
--
应用于a
,因此a
的新值为0
。如果再添加一个-
,那么a
的值减去1
后,就会减去b
的值> 产生-2
-
and--
are unary operators. Therefore can't be used with two operands. That's whyis wrong.
--
is applied toa
, so the new value ofa
is0
. If you add one more-
, then the value ofa
decremented by1
will be subtracted by the value ofb
yielding-2