Question

Suppose we have the following code snippet in Java:

int a = 3;
int b = a++;

The value of a gets assigned to b first and then it gets incremented. b = 3 and a = 4. Then why does the postfix expression get evaluated from right to left? Wouldn't it make more sense for it to be evaluated from left to right?

Was it helpful?

Solution 2

There seems to be some kind of confusion here. Java always evaluates from left to right (or to be more precise, always pretends to do so), as stated in the JLS here:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

What you're talking about is the direction of associativity, that is if an operand is sandwiched between two operations of the same precedence, which one is the operand bound to. So the ternary operator for example is right-associated because if you've got a?b?c:d:e, you expect it to resolve to a?(b?c:d):e

But the postfix ++, on the same precedence level as the '.' operator is left-to-right associated, which is why foo.bar++ works.

The prefix ++ is indeed right grouping because ++++x should really be `++(++x). Since it's a unary operator and the operand is to the right, it must group to the right.

OTHER TIPS

The postfix operators are not evaluated right-to-left; their side-effect happen after the value is determined (roughly speaking - the JLS specifies the order).

Actually: No. This is the expected behaviour. Compare a++ with ++a. If you would do the last one, you would get a=4, b=4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top