• 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

KB Question pg 314

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


Can anyone explain me this code pleasee, not getting

Output is : 8,2
 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the expression a || b, first left side (a) is evaluated, and if it is 'true', then the right side is skipped, because for a || b, if only a=true then the whole expression is true.
Simillary for a && b, if a=false, then only only the left side (a) is evaluated (executed) and (b) is skipped.

This is not true for a | b and a & c expressions - in these cases compiler always evaluates boths sides (a and b).

So, look how the 'for' loop is executed:

1. z = 0, x = 0, y = 0
++x > 2 (x=1) --> false, ++y > 2 (y=1) -->false
2. z = 1, x = 1, y = 1
++x > 2 (x=2) --> false, ++y > 2 (y=2) -->false
3. z = 2, x = 2, y = 2
++x > 2 (x=3) --> true!! - so don't evaluate ++y > 2 (y=2)!!
whole if condition is true --> execute x++ (x=4)
4. z = 3, x = 4, y = 2
the same as point 3 - x is incremented twice, and y is unchanged
5. z = 4, x = 6, y = 2
the same as in 3 - x is incremented twice, and y is unchanged

in the end, z=5, x=8 and y=2
[ June 23, 2008: Message edited by: Ireneusz Kordal ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic