• 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

Operator evaluation order

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all

Can someone explain the order of evaluation and how y holds the value 0.
Thanx in advance
Alexan
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
x = -1
y= x++ + ++x
operands are always evaluated from left to right
before an operation is performed all the operands are
evaluated except in conditional operators such as (&& , || and in some cases of ?
then the operation is performed based on precedence
ans associativity.
before addition could be performed both the operand has to be
evaluated
Left operand
x++ is evaluated . since it is postfix expression the vlaue of the expression is the value of x before
the increment is performed. so the expression will get the value -1(which is the value of x before increment) but x will be incremented by one
so x will be -1+1=0.
Right operand
++x is evaluated . since it is prefixx expression the value of the expression is the value of x after
the increment is performed. so the expression will get the incremented value of x that is 1.
Left expression + Right expression
-1 + 1 = 0
so y=0
x =1
hope this helps
Saravanakumar R
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Alexan:
First the postfix and prefix operators are evaluated and the added together as they have higher precedence over addition.
So coming back to your question:
int x = -1;
y = x++ + ++x;
This would be evaluated as:
y = -1 + 1
y = 0
The postfix operator (x++) gets the value -1 first and then x is incremented by 1 to give 0.
The prefix operator (++x) adds 1 to x first, then uses the new value of x as the value of the expresiion.
Hope this helps.
Emad
 
Destiny's powerful hand has made the bed of my future. And this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic