Jump to content
  • Advertisement
Sign in to follow this  

Operator Precedence

This topic is 2836 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all -

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,


Share this post

Link to post
Share on other sites
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 *

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!