Java – left to right evaluation of expression and operator priority Why does the left to right assessment seem to win?

Consider the following codes:

public class Incrdecr {

static int x = 3;
static int y = ++x * 5 / x-- + --x;

public static void main(String[] args){

    System.out.println("x is " + x);
    System.out.println("y is " + y);
}

It assesses the following:

x is 2
y is 7

This makes sense, but let's take a quick look at the operator priority table:

Therefore, the suffix operator should be evaluated first Now, if we go back to our code, we'll see that X - should be evaluated first, but that's not the case I don't remember what?

In other words, if we strictly follow the operator priority table, the expression will evaluate as:

y = x * 5/3 –x;

Of course, this gives us a completely different result

Solution

Your expression is correct from left to right This is the general evaluation order in Java (with possible exceptions)

I think you've figured out what happened:

>X is incremented from 3 to 4, and the new value 4 > 5 is evaluated as 5 > 4 * 5 = 20 > x, and the value of 4 is used for division; Division yields 5, and X decreases to 3. > X is further decremented to 2 before the value of the final addition, and then 7

Exception: the compiler is allowed to swap steps only if the same results can be guaranteed So we know the result can only be 7

Try to distinguish between two concepts: evaluation order and operator priority They are different

The precedence table tells you that the expression is understood as ((x) * 5 / (x –) (– x) (this is mostly good because (x * 5 / x) –– x doesn't make sense anyway)

Take a different example: F (x) – g (x) * H (x) Mehtods calls from left to right: F (), then G () and H () The priority table only tells you that multiplication is done before subtraction

Editor: in his comments, Lew Bloch questioned that x would be evaluated as 4 at any time in the calculation process To test this, I proposed the following program variants from the question:

public class Incrdecr {

    static int x = 3;
    static int y = p(++x) * 5 / p(x--) + p(--x);

    private static int p(int i) {
        System.out.println("p(): " + i);
        return i;
    }

    public static void main(String[] args) {
        System.out.println("x is " + x);
        System.out.println("y is " + y);
    }
}

This print:

p(): 4
p(): 4
p(): 2
x is 2
y is 7

So yes, at two points x is evaluated as 4

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>