This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question on operator precedence

 
Vin Kris
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys
I find myself going back to the basics day by day.
if the postfix operator precedence is much higher than the equality (==) operator, then in the following code:
int i = 0;
while( i++ == 0 ) System.out.print(i);
System.out.print(i);
shouldn't the expression be treated as follows?
while( (i++) == 0 ) System.out.print(i) ??
BUT the the value is first compared and then incremented. The output is therefore '12'.
 
zarina mohammad
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In the post increment i++ the value of i that is used in the calculation is the original value ,increment or decrement only occurs only after the expression is calculated.
hence the output will be 1
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A postfix operator will return the original value first before incrementing.
In while( i++ == 0 ), you have ( 0 == 0)
After this boolean statement executes, i is now equal to 1 and System.out.print(1). The while condition is now false so the next stament is executed, which is System.out.print(2);
[ August 22, 2002: Message edited by: Anthony Villanueva ]
 
Vin Kris
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Zarina & Anthony.
I understand the reason for the output. But My question was regarding the operator precedence.
The precedence of the postfix operator is higher than the equality operator. In this case, shouldn't the value be incremented before comparison? according to the precedence table?
Thanks.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i is incremented before the comparison, but the comparison will still use the old value of i.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic