括号在 post 递减或递增的组合中是否重要,如下所示:x+=(x++)+(++x);

Does brackets matter in a combination of post decrement or increment like this one: x+=(x++)+(++x);

下面的程序在post自增或自减

的语句中是否需要括号
public class sample
{
  public void f1()
  {
    int x=4;
    x+=(x++)+(++x);
System.out.println(x);
  }
}

^^这个等于

public class sample
{
  public void f1()
  {
    int x=4;
    x+= x++ + ++x;
System.out.println(x);
  }
}

没有必要使用括号。前缀和后缀 ++ 的优先级均高于 +.

但是,有必要使用一些东西来分隔 +++ 运算符。如果您不将它们分开(使用空格、注释或其他标记),您会得到一个相当混乱的编译错误。例如:

Test.java:3: error: unexpected type
    int j = i +++++ i;
              ^
  required: variable
  found:    value
1 error

这是正在发生的事情:

  1. 词法分析器读取上面的内容为int j = i ++ ++ + i ;。这是 JLS 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."

  2. 考虑到优先级,解析器将表达式解析为:

                 +
                / \
              ++   i
              /
            ++
            /
           i
    

    其中 ++ 是后缀递增运算符。那相当于((i++)++) + i.

  3. 分析器检测到后缀 ++ 被应用到 i++ 的结果,这是一个值。那是非法的。 ++ 的操作数必须是变量而不是值。

    正如JLS 15.14.2所说:

    "The result of the [operand] must be a variable of a type that is convertible to a numeric type, or a compile-time error occurs."


但是说真的,不要这样写代码。这只是令人困惑......而且没有必要。

不需要括号,但您确实需要分隔 +s。

Java 在解析时使用 maximal munch。这意味着它会消耗尽可能多的文本来制作标记。

因此,例如,

+++++

被解析为

++ ++ +

这毫无意义(post 增量结果不是 l 值)因此编译器发出诊断。

++ + ++ 中应用正常的分组规则(非正式地说,运算符优先级),因此整个表达式按照您在第一个片段中的分组方式进行分组。

你不应该写这样的代码。我想不出这个有什么用,它让 reader.

感到困惑

写一些测试代码很容易找到答案,但没关系。