Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

pre/post increment / decrement operators

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I having a problem understanding pre and post operators. I can understand the following simple code:

still results 0 because it is increment after it is assigned to i. But take a look at this more complex version:

every way I look at it, i keep getting different answers! How does one work out the results for this kind of question?
To me I would have thought that starting from the left, it would first (++n) to get a three, then n++ still leaves it three because it is added after, then --n to 2, and again --n to get one, finally incrementing the earlier post operator n++ to get a four (because it was 3 at that point). Finally add all the results, 3+4+2+1 = 10, but the answer is 11?
Any help would be gratefully appreciated, especially any rules of how it works.
Also, how does one KNOW when the object is garbaged collected at a certain point?
Thanks!
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you almost did it right:
++n + n++ + --n + --n;
++n gives u 3 as u said.
then at n++ it is still 3 u are correct so the answer until now is 6.
now: --n. u must remember that n at this point is 4 (bacsue in the last stage u did n++ so it was inceremnted after the addiotion to 6 u did).
so now n is 3 again so the answer is 9.
at last:
--n now n is 2 so the answer is 11.
3+3+3+2=11; !
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this link out:http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014606
HIH
 
Darren Tweedale
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh, I see now! It is all crystal clear now!
Thanks all the info. Bye
 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dareen, I wrote a POST couple of days ago on the post=fix operators:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014701
 
    Bookmark Topic Watch Topic
  • New Topic