• Post Reply Bookmark Topic Watch Topic
  • New Topic

Increment  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I tried this code.



The output printed is 10 and not 11. After first increment value gets incremented to 10. That is understood. But for post increment even the increment happens after assigning it to variable on left side of '=', the incremented value should get stored in 'i' thereby making it 11. In C/C++ , it prints 11 as expected but how come in Java the value remains 10.
Please help clear this doubt

Thanks
 
Ranch Hand
Posts: 121
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello
Please refer here
This cleared my doubt also .
This would help.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
virtualsaum huk wrote: . . . In C/C++ , it prints 11 as expected but how come in Java the value remains 10. . . .
No, it doesn't. The value in C is undefined, so there is no such thing as "as expected". In fact I once tried something similar with three different C compilers, starting with 4. The output from two of the compilers printed 4 and from one 5, for exactly the same code
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
virtualsaum huk wrote: . . . the increment happens after assigning it to variable on left side of '=', . . .
No, it doesn't. Postincrement has the highest precedence of any operator, so the postincrement is performed before the assignment. It is not at all easy to understand, because the increment is applied to i. The value of i++, however, remains equal to the old value of i. So after incrementing i, you are re-assigning it its old value.

Marlene Miller's postings in that old thread are good.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!