Members - Reputation: 201
Posted 16 January 2012 - 10:18 AM
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?
Thanks ahead of time for the answer,
Members - Reputation: 152
Posted 16 January 2012 - 01:32 PM
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 *
Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/
Moderators - Reputation: 10651
Posted 16 January 2012 - 03:40 PM
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.