• 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
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

Precedence

 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone shed some light here please, I'm desperate

y is 0!
I thought it would be y=-1 + 0 but it seems to be y=-1 + 1.
How come??
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is evaluated left to right:
1. y = x++ (At this point y = -1 and x now equals 0)
2. y = y + ++x (Now y = 0 and x = 1)
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just a guess, I think here's what happened:
x=-1
y=x++ + ++ x; // x= -1
x++ has the most precedence, so it becomes:
y= (-1) + ++x; // x = 0
++x is next:
y = (-1) + (1);
therefore the result is 0.
It is interesting to compare this with:
x = -1;
x += x++;
Which will give -2, in my mind the += operator works like:
int tmp = x;
x = tmp + x++;
Hope this helps and the above is correct...
Adrian
 
Bojan Knezovic
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Michael Morris:
It is evaluated left to right:
1. y = x++ (At this point y = -1 and x now equals 0)
2. y = y + ++x (Now y = 0 and x = 1)



I thought x gets inceremented only AFTER the = operator (for #1, x++), isn't that what's pre and postfix notation all about... Oh well... :roll:
I thank you and Adrian.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic