• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Increment

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello
Please refer here
This cleared my doubt also .
This would help.
 
Marshal
Posts: 80295
434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 80295
434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Space pants. Tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic