I had a question about operator precedence in Java. I'm reading Java: How to Program by Deitel and Deitel 9/e. In this book they have an appendix on operator precedence and something doesn't make sense to me, I was hoping someone here could clear it up.
I understand the order of almost everything except where they have listed postfix operators as the highest precedence. If this is operation happens afterwards why is it listed as highest precedence?
I think what is means is if you have the following line:
x=2*x++; //x=5 before execution
It will evaluate the ++ (postfix) first, which says increase the value of x after this line is executed.
Then it will do the multiplication, (2*x=10)
And then assign the new value to x (10).
Then, the postfix kicks in, increasing x by one (11).
If, on the other hand, the * had precedence over the ++, it would try to do (2*x)++. This is like writing
2*x=2*x*1 (You can't assign a value to a non-variable).
Executing a postfix expression like x++; is not saying "increase the value of x by one", it is saying "after this line executes, increase x by one".
Or just look at parentheses, which is equivalent to 2*x++
(2*x)++ // * takes precedence over ++
2*(x++) // ++ takes precedence over *
A penny for my thoughts? Do you think I have only half a brain?
It has more relevance in languages that allow references to primitives or operator overloading. But simply put, the operator precedence determines which sub-expressions the operator is bound to. The pre/post fix operations are a separate affair.
In general, you should avoid such complex expressions because they are bug prone. In particular, a maintainer can only see the expression as it was implemented, but not what was intended. To clarify intent, use parentheses or break the expression into smaller, easier to understand chunks.