Jump to content

  • Log In with Google      Sign In   
  • Create Account

Operator Precedence


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 Spyderzone   Members   -  Reputation: 182

Like
0Likes
Like

Posted 16 January 2012 - 10:18 AM

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,

~Mike

Sponsor:

#2 HelloSkitty   Members   -  Reputation: 152

Like
1Likes
Like

Posted 16 January 2012 - 01:32 PM

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 ++
or
2*(x++) // ++ takes precedence over *
A penny for my thoughts? Do you think I have only half a brain?

Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/

#3 rip-off   Moderators   -  Reputation: 8727

Like
0Likes
Like

Posted 16 January 2012 - 03:40 PM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS