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

    Join Date
    Aug 2013
    Posts
    15
    Rep Power
    0

    Expression solving


    #include<stdio.h>
    int main()
    {
    int i=-3,j=2,k=0,m;
    m=++i||++j&&++k;
    printf("%d%d%d%d\n",i,j,k,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
    Posts
    4,379
    Rep Power
    1871
    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
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    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