Java 编译器是否存在 "assignment has no effect" warning/error 的错误

Does the Java compiler has bug with "assignment has no effect" warning/error

似乎 java 编译器 (Jdk8) 缺少对 'j = j++;' 等无效赋值的警告,而是为 'j = ++j;' 等实际有效的赋值生成警告.我附上了一个演示脚本。

请注意,您必须 select 在 java 编译器 java compiler settings

中报告分配错误的适当标志
public static void main(String[] args) {
    int j = 0;
    j = ++j; //Compiler warning: The assignment to variable j has no effect
    System.out.println("j="+j); //Prints 1

    int i = 0;
    i = i++; //Compiler warning: 'None'     
    System.out.println("i="+i); //Prints 0
}

这是 java 编译器的错误吗?

但是警告和缺少警告是正确的:

  • j = ++jj =部分没有作用; j 中已有更新值。所以警告是有道理的。
  • 但是i = i++i =部分确实有作用:i递增到1后,赋值为0 — 右侧表达式的结果。所以 "has no effect" 警告不仅不需要,而且是错误的。

对于 i 情况,您可能有一个不同的警告参数,但一般来说,编译器不会进行大量的 linting(检查可能是逻辑错误但不是逻辑错误的事情) 't 语言 错误)。

我应该注意到,OpenJDK 编译器根本不会针对给定代码发出任何警告。 Eclipse 有自己的编译器,该编译器会发出更多警告,所以...您可能想向他们提出请求,为 i = i++ 情况添加警告,例如 "Side effects in right-hand expression are negated by assignment" 或类似的.