Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

about ++ ??  RSS feed

 
Chen SanHau
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

result
012345678910
012345678910
It seems that i++ or ++i make no difference here ?
In what situation will i++ or ++i in for(...) will get different results
in {...}??


In Java, JVM would allocate new memory to operation when ++ after a field, but would not allocate new memory to operation when ++ before a field.
So after i = i++; ,I get i=0.
Am I right ??
Thanks anykind of help!!
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do believe that you are understanding the differences between the post-increment and pre-increment operators in Java.
i = i++; // i=0, question??
Assuming that i was 0 before this line...
Remember that the assignment operator has the lowest precedence, that expressions in Java have a resultant value (sometimes called a return value), and that the right side of an assignment operation is evaluated before the left side.
In this example, first i++ is evaluated and the resultant value is 0. This value will be used later during the assignment, which is the last operation performed.
Next, the post-increment operator is performed, and i has a value of 1, but only for a fleeting moment.
Finally, the assignment operation is performed, and i is assigned the value that the expression i++ evaluated to, which was 0.
Get it?
i = ++i; // i=1, question??
Prior to the expression right of the = operator, ++i, being completely evaluated for a value to use during the assignment operation, the pre-increment operator is performed and i is given a value of 1.
Now, the expression right of the = operator is evaluated to have a resultant (or return) value of 1, because that's the current value of i.
This value of 1 is then assigned to i, completing the assignment operation.
The real lesson in all of this is to learn to not write code as in these two examples. Code should be very clear and easy to understand. Try to avoid compound assignments, especially when they get tricky.
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for the first part of your question, you can try this...

Which will give you the same result as i++ and ++i
This one however...

Will be an infinite loop.
To understand how postfix and prefix operators work try this link.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!