• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Order of Evaluation for pre and post increment operators

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Whats the order of evaluation?


Output :
5 3

What is the right output :
1+2+2=5
(or)
1+1+3=5
 
Greenhorn
Posts: 19
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Initially value of i=0;

now , int x=++i
i=0 initial
i=1 final

int x= ++i + i++
i=0 initial i=1 (initial)
i=1 final i=2(final)


int x= ++i + i++ + ++i
i=0 initial i=1 (initial) i=3(initial)
i=1 final i=1 (final; but i=2 will go) i=3 (final;i 's value)

1+1+3=5 (x's value)


....hope that helps

 
lowercase baba
Posts: 13091
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mohnish Khiani wrote:

What is the right output :
1+2+2=5
(or)
1+1+3=5


Wouldn't it have been easier to run the code yourself and find out?
 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i have executed the code and know the output is 5,but i wanted to know how?

That means evaluation is from left to right no matter pre or post operators?
 
Sheriff
Posts: 22841
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Correct. That code is equivalent to this:
But this also shows how dangerous it can be to use pre and post increment operators inside other statements. It's very easy to loose track of what's going on.
 
reply
    Bookmark Topic Watch Topic
  • New Topic