1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

help with expression

Discussion in 'C' started by eilon, Aug 29, 2014.

  1. eilon

    eilon New Member

    Joined:
    Aug 28, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    i have this code

    int i=3;
    int j=(++x)*(++x);

    now j become 25, why?
    cant explain it, why not 4*5=20?
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    Because value is incremented and then applied to the expression.

    It also depends on parser to parser but most of them would result in 25
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    The behaviour is undefined. All the standard says about preincrement is that the variable is incremented before it is used; it does not say WHEN it is incremented. So it could be equivalent to 4*5 as you expect, but it could equally be equivalent to ++x; ++x; int j=x*x; which gives 25.
     
    shabbir likes this.
  4. eilon

    eilon New Member

    Joined:
    Aug 28, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0

Share This Page