Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operator Precedence - Confused

 
Tresa Antony
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Could you please help me understand whats happening here? Why does it print 0 and not 1?



Also, let

int a=1,b=5;

In the expression (a++ < b--) , does a++ and b-- happen first and then the 'less than' comparison?

Ta
 
Patrick Joseph
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i++ is postfix notation.

So i is incremented only after the original value of i is used in the expression i=i++;

Hope that explains it...
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, evaluate the value of i. Store that on top of the stack. (0)
Next, increment i (through the post-fix operator). i now equals 1.
Now, perform the assignment. Assign i the value on top of the stack (0).

Now, i = 0.

Post-fix notation happens after the evaluation of the variable, but before the assignment.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the expression (a++ < b--) , does a++ and b-- happen first and then the 'less than' comparison?

Yes, but the comparison uses the original values of a and b.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my opinion, this is a terrible way to write code. As a rule of thumb, you should limit the number of side-effects (changes to values in variables) to one per line of code. I cannot think of any situation where "i=i++" would even be useful. Although, I could imagine where "a++ < b--" might be tempting, I would instead do something like this:

Of course, if the new values of a and b are needed in the body of the if statement, the increment and decrement would need to be inside the body rather than after it. However, the point is to separate these side-effects into separate statements. It will make the code much easier to read and maintain.

Keep Coding!

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic