为什么n +++ n有效而n ++++ n不是? [英] Why is n+++n valid while n++++n is not?

查看:177
本文介绍了为什么n +++ n有效而n ++++ n不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,表达式为:

In Java, the expression:

n+++n

似乎评估为等价于:

n++ + n

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

Despite the fact that +n is a valid unary operator with higher precedence than the arithmetic + operator in n + n. So the compiler appears to be assuming that the operator cannot be the unary operator and resolving the expression.

但是,表达式为:

n++++n

不编译,即使有一个有效的可能性,它可以解决为:

Does not compile, even though there is a single valid possibility for it to be resolved as:

n++ + +n

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

++n and +n are specified as having the same precedence, so why does the compiler resolve the seeming ambiguity in n+++n in favour of the arithmetic + but does not do so with n++++n?

推荐答案

首先使用最大munch规则对文件进行标记化(转换为标记序列) - 始终获得最长的有效标记。您的文本将转换为以下序列:

The file is tokenized (transformed into sequence of tokens) first with the maximal munch rule - always get longest possible valid token. Your text is transformed to following sequence:

n ++ ++ n

这不是有效的表达式。

来自JLS§3.2


3.2。词汇翻译



使用以下三个
词汇翻译步骤将原始Unicode字符流转换为一系列标记,这些步骤依次应用:

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. 将Unicode
    字符的原始流中的Unicode转义(第3.3节)转换为相应的Unicode字符。形式为\uxxxx的Unicode转义
    ,其中xxxx是十六进制值,表示编码为xxxx的UTF-16代码单元
    。此转换步骤
    允许任何程序仅使用ASCII字符表示。

  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.

将步骤1产生的Unicode流转换为流输入字符和行终止符(第3.4节)。

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

将步骤2产生的输入字符和行终止符流转换为输入元素序列
(§3.5),在空格(§3.6)和注释(§3.7)被丢弃的
之后,包含作为句法语法的终止符号
的标记(§3.5)( §2.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).

每个步骤都使用尽可能长的翻译,即使结果不是最终制作一个正确的节目,而另一个
词汇翻译。

(因此,输入字符 a - b 被标记化(§3.5)为 a, - ,b
,这不是任何语法正确的程序的一部分,即使
标记化 a, - , - ,b 可以是语法正确的
程序的一部分。)

(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.)

这篇关于为什么n +++ n有效而n ++++ n不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆