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

mike :

It seems that the java compiler (Jdk8) missing the warning for assignments like 'j = j++;' that have no effect but instead it generates warnings for assignments like 'j = ++j;' that actually have effect. I have attached a script for demonstration.

Please note that you have to select the appropriate flag for reporting the assignment errors within java compiler 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
}

Is this a bug of java compiler?

T.J. Crowder :

But the warning and the lack of warning is correct:

  • The j = part of j = ++j has no effect; j already has the updated value in it. So a warning makes sense.
  • But the i = part of i = i++ does have an effect: After i is incremented to 1, it's assigned the value 0 — the result of the right-hand expression. So a "has no effect" warning isn't only not called for, it would be wrong.

You might have an argument for a different warning for the i case, but in general, the compiler doesn't do a huge amount of linting (checking for things that are likely logical errors but which aren't language errors).

I should note that the OpenJDK compiler doesn't issue any warnings at all for the given code. Eclipse has its own compiler, and that compiler does do more warnings, so...you might want to raise a request with them to add a warning for the i = i++ case, something like "Side effects in right-hand expression are negated by assignment" or some such.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306977&siteId=1