Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Any body explanation why ...

 
Pradeep Kalyan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does the following program return 10 as output. In C or C++, the same code returns 11.

i = i++ ;
System.out.println("output i: " + i);

Does any body explain what's going on here?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume that i is initially 10. The right-hand side is a post-increment, so its value as an expression is the value of i before the increment. So i is incremented by 1, but set back to 10.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll just add a little bit of detail to what Keith said (again assuming that i is 10).

i = i++; is a simple assignment, so first the "left-hand operand is evaluated to produce a variable." In this case, i. (See JLS - 15.26.1.)

Next, the right hand-hand operand is evaluated. With a postfix operator, the term i++ evaluates to 10, after which i is incremented to 11. (See JLS - 15.14.2.)

Finally, because the right-hand operand evaluated to 10, the value 10 is stored into the varaible i.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code

does nothing (at least in siglethreaded program). In both Java and C.
 
Shaliey Gowtham
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please have a look at assembly level
intially i = 10;
i = i++ can be split as
load i on stack; \\top = 10
increment the variable locally for i++; \\ i = 11
now store the value on top of stack into i; \\ i = 10;
So the final result is i = 10;
For i++ instruction the value is not brought to the stack,but
incremented at the location through inc 1

But if i = i + 1, then
load i on stack; \\ top = 10
add one to top of stack; \\top = 11 (10+1)
store the value on top of stack into i; \\ i = 11

Hope you are clear
 
ashok ch
Greenhorn
Posts: 11
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello "ashok"-

Welcome to JavaRanch.

On your way in you may have missed that JavaRanch has a policy on display names, and yours does not comply with it - please adjust it accordingly, which you can do right here. Thanks for your prompt attention to this matter.

Enjoy your time here.
 
dai jiansong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what a good example!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic