• Post Reply Bookmark Topic Watch Topic
  • New Topic

post-increment operator  RSS feed

 
Joseph Maddison
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following example might be surprising. It comes from http://www.jchq.net/mockexams/exam3.htm, question 54...



Evaluating the line in bold, I would have guessed that the right-hand side gets evaluated to 0, is assigned to i on the left, then i on the right gets incremented, therefore i = 1. In fact, the answer is 0. Why?

Thanks,
jdmaddison
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the hidden assignment in the post-increment operator happens BEFORE the explicit assignment. In other words, the computer somehow does the task in the following order:

1) store the current value of i (i.e. 0)
2) increment i and store this new value in i
3) assign the temporary value (0) to the variable i

Steps 1 and 2 evaluate the post-increment. Step 3 evaluates the assignment.

HTH

Layne
[ January 23, 2005: Message edited by: Layne Lund ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!