1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Rep Power

    Expression solving

    int main()
    int i=-3,j=2,k=0,m;
    return 0;

    In the above program we get the output as
    -2 -2 0 1

    how is this expression solved and we get this answer?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    Well the first step is to understand short circuit evaluation
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Woodland Hills, Los Angeles County, California, USA
    Rep Power
    My output is -2201. The result is because of C's short-circuit evaluation. Once it evaluates that ++i is non-zero, the rest of the expression doesn't need to be evaluated because the || will be true regardless of what the value of the other expressions are.

    Of course, this behavior may be compiler specific. Also note that when I compile it on gcc with full warnings, it warns me with this message:
    warning: suggest parentheses around && within ||

    Best not to write code like this if you have trouble trying to figure it out yourself.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo