javacompiler-warningsjavacecj

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


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?


Solution

  • But the warning and the lack of warning is correct:

    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.