gpt4 book ai didi

java 。算术运算.标记化。如何?

转载 作者:搜寻专家 更新时间:2023-11-01 02:54:39 25 4
gpt4 key购买 nike

谁能解释一下或给出一个很好的引用来理解这个例子:

int a=1;
int b=2;
System.out.println(a---b); //correct
System.out.println(a- -b); //correct
System.out.println(a--b); //wrong

谢谢。

最佳答案

表达式 a---b 没有(如您所料)解析为 a-(-(-b)) 而是解析为 ( a--) - b.

这个例子说明了这一点:

int a = 0;
int b = 0;
System.out.println(a---b); // prints 0
System.out.println(a); // prints -1

考虑到这种行为,a--b 被解析为 (a--)b,这显然是一个错误。

当你在减号之间放置一个空格时,a- -b 它不再被解析为 -- 运算符,而是作为二元和一元减号:a - (-b).

请注意,您可以编写 a- - -b,它被解释为 a-(-(-b))

那么为什么会这样解释呢?那么@EJP 对另一个答案给出了很好的评论。在JLS, section 3.2您可以阅读以下内容:

The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would. Thus the input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.

关于 java 。算术运算.标记化。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com