Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

? i=++i ?

 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all:
public class test {
public static void main(String args[]) {
int i=0, j=2;
do {
i=++i;
j--;
} while(j>0);
System.out.println(i);
}
}
output is 0.
Why? What happened on i=++i?
Thanks
Roger
 
Dan Lastoria
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output is actually 2, not 0.
Maybe you printed out j by accident?
[ August 19, 2003: Message edited by: Dan Lastoria ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the ++i is changed to i++, then the output is indeed 0. Roger, did you post the example code correctly?
 
Dan Lastoria
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the statement was this instead:
i = i++;
Then that makes sense...it's just a matter of operator precedence. The last thing this statement actually does is set i to the pre-incremented value of i++. The actual value of i is then 0.
In other words:
i on the right hand side evaluates to 0 during this expression. It is not incremented until after the expression completes.
However the = operator has a lower precedence than the ++ operator.
So the ++ changes i = 1
But then the = operator assigns i = 0, the value that i is throughout the expression. Remember it doesn't get incremented until after the expression is completed. However the increment is lost since you performed an assignment (lower precedence).
Confusing, I know. Hard for me to explain. That's why I rarely use postfix or prefix increments within expressions. I typically use them "stand-alone".
 
Dan Lastoria
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking at this might help too:

This snippet will print:
m is: 5
k is: 6
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To repeat myself and others from previous conversations on similar topics, the real lesson here shouldn't be to understand exactly what happens in statements such as i = ++i or i = i++, but to learn to not write code in such a manner. Code should be clear to the humans that read it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic