Java语法+ [英] Java syntax of +

查看:134
本文介绍了Java语法+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下语法正确

x = y+++y;




这意味着 y ++ + y y + ++ y 这意味着 y * 2 + 1 (不确定,虽然:非常含糊不清)

Where it means y++ + y or y + ++y which means y * 2 + 1 (not sure about this, though: very ambiguous)

但这种语法不正确

x = y+++++y;




这应该是指 y ++ + ++ y ,表示 y * 2 + 2

这种语法的错误是否有原因? (编辑:谢谢你解释为什么它是无效的语法,但这不是我对这个问题的意图。)

Is there a reason for the incorrectness of this syntax? ( thank you for explaining why it is invalid syntax, but that is not my intention with this question.)

编辑: ofcourse我不是在真正的代码中使用它,纯粹是为了解析器/词法分析器;但我想知道为什么解析器不喜欢这个;最后一个例子甚至看起来不像第一个那么模糊。)

( ofcourse I'm not using this in real code, purely in interest of parsers/lexers; but I wonder why the parser doesn't like this; the last example even looks less ambiguous than the first one.)

编辑:

    int i = 0;
    int j = (i = 3)+++i;

也是无效的,虽然它对我来说似乎非常明确,(i = 3)是一个值,因此(值 + value)然后是 ++ i 价值代币。)

Is invalid too, though it seems very unambiguous to me, (i = 3) is a value, thus (value + value) and then the ++i value token.)

推荐答案

解析是贪婪的,也就是说,它首先寻找最长的匹配令牌。这大大简化了实现(大概)。此外, Java语言规范(3.2)说

The parsing is greedy, that is , it looks for the longest matching token first. This simplify the implementations a lot (presumably). Also the Java language spec(3.2) says


Java总是在每一步使用尽可能长的
翻译,即使
结果最终没有赚到
正确的Java程序,而另一个
词汇翻译

Java always uses the longest possible translation at each step, even if the result does not ultimately make a correct Java program, while another lexical translation would

所以,对于 y + ++++ y; 解析器/标记器会将其分解为:

So, for y+++++y; the parser/tokenizer will break it down something like this:


  • 变量 y

  • 运营商 ++ (因为没有 +++ 运算符, ++ 是与java语法匹配的最长的语句。

  • operator ++ (因为没有 +++ 运算符, ++ 是与java语法匹配的最长的)

  • operator + (这是第一个与语法匹配的东西)

  • 变量 y

  • variable y
  • operator ++ (as there is no +++ operator, ++ is the longest that match the syntax of java)
  • operator ++ (as there is no +++ operator, ++ is the longest that match the syntax of java)
  • operator + (This was the first thing that matches the syntax now)
  • variable y

实际上它被解析为(y ++)(++)(+ y)
++ 为变量定义了运算符,但第一个表达式( y ++ )返回一个值。您不能将下一个运算符( ++ )应用于某个值。

Effectively it is parsed as (y++) (++) (+y) the ++ operator is defined for a variable, however the first expression (y++) returns a value. You can't apply the next operator (++) to a value.

这意味着 x = y +++ y; 将被解析为 y ++ + y ,这没有任何问题。

This means that x = y+++y; would be parsed as y++ + y, which is nothing wrong with.

这篇关于Java语法+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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