• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Postfix increment in while condition

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is bugging me...

Why does this snippet print 13 and not 12? I thought first iteration i = 10, then enter while loop, then i = 11 then postfix operator makes i = 12 and don't enter while again and finally print 12.



Ideas?
Thanks
 
Bartender
Posts: 3648
16
Android Mac OS X Firefox Browser Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Rule about pre/post-fix in/decrement:
i++ or i-- = postfix = assign then increment/decrement
++i or --i = prefix = increment/decrement then assign

[edit]
looking at the while loop, given i=10 (postfix)
first iteration the checking is 10<=10 and this is true, the i increments to 11
inside the loop i gets increments again now i=12

second iteration the checking is 12<=10 and this is false, the i increments to 13 exit loop

prints 13.
 
Anda Popovici
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Saw your edit.

Yes, I wasn't considering i would be incremented again after the second condition.

Thank you !
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right, there are three more runs of i++ after the one in which i <= 10.

Regards,
Dan
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic