gpt4 book ai didi

java - 为什么 n+++n 有效而 n++++n 无效?

转载 作者:太空狗 更新时间:2023-10-29 22:54:46 29 4
gpt4 key购买 nike

在 Java 中,表达式:

n+++n

似乎评估为等同于:

n++ + n

尽管 +n 是一个有效的一元运算符,其优先级高于 n + n 中的算术 + 运算符。因此编译器似乎假设运算符不能是一元运算符并解析表达式。

但是,表达式:

n++++n

不编译,即使有一个有效的可能性将其解析为:

n++ + +n

++n+n 被指定为具有相同的优先级,那么为什么编译器要解决 n+++n< 中看似歧义的问题 支持算术 + 但不支持 n++++n?

最佳答案

首先使用最大咀嚼规则对文件进行标记化(转换为标记序列)——总是获得尽可能长的有效标记。您的文本将转换为以下序列:

n ++ ++ n

这不是有效的表达。

来自 JLS §3.2 :

3.2. Lexical Translations

A raw Unicode character stream is translated into a sequence of tokens, using the following three lexical translation steps, which are applied in turn:

  1. A translation of Unicode escapes (§3.3) in the raw stream of Unicode characters to the corresponding Unicode character. A Unicode escape of the form \uxxxx, where xxxx is a hexadecimal value, represents the UTF-16 code unit whose encoding is xxxx. This translation step allows any program to be expressed using only ASCII characters.

  2. A translation of the Unicode stream resulting from step 1 into a stream of input characters and line terminators (§3.4).

  3. A translation of the stream of input characters and line terminators resulting from step 2 into a sequence of input elements (§3.5) which, after white space (§3.6) and comments (§3.7) are discarded, comprise the tokens (§3.5) that are the terminal symbols of the syntactic grammar (§2.3).

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 - 为什么 n+++n 有效而 n++++n 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18643939/

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