11
I have a question regarding the precedence of operators in Java. I have the following code:
int x = 2;
long y = 1 + x * 4 - ++x;
Viewing the Precedence Table here.
In my view the expression should be resolved as follows:
1 + x * 4 - 3
1 + 3 * 4 - 3
1 + 12 - 3
y=10
Contrary to what I have said, the answer given by the implementing programme is y=6
. I wonder why he performed the multiplication before the increment?
By the precedence table, increment in my view should be performed first.
Even if the sum and subtraction operators associated to the right, the relative execution order between
x*4
and++x
would still be the same.1 + ((x * 4) - (++x))
. And in this particular case, even the result would be the same (it would not be the case if the first operator were a-
)– mgibsonbr
Yes, in this case yes, but what he is imagining is that there is no associativity and the expression is evaluated as a whole. He thinks that because the increment is precedent he should be evaluated first even being on the right, and then go to the other operators.
– Maniero
I think I know what you mean. In fact, an expression without side effects could be evaluated in the order "leaves first, rising toward the root" (i.e. most previous operations being applied before the least preceding), and the result would be the same as "left branch first, right branch after". With side effects, the results are different. But note that this is an arbitrary convention imposed by the programming language, because the way to include parentheses according to precedence and associativity would be the same in both cases.
– mgibsonbr
Yes, I agree..
– Maniero