Query in precedence

Discussion in 'C' started by coolmesh84, Jul 20, 2009.

  1. coolmesh84

    coolmesh84 New Member

    Joined:
    Jul 20, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi
    I was just running a snippet from this website.

    Code:
    int a=10,b;
    b=a++ + ++a;
    printf("%d,%d,%d,%d",b,a++,a,++a);
    
    I expected the answer to be 22, 13,13,13
    But when i ran through VS 2005, I got 22,13,14,14.

    Am I missing anything??

    Mesh
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    The behaviour is undefined because you use side effect operators twice on the same variable in the same statement. Twice.

    This means the behaviour is dependent on what the compiler writer felt like at the time and should be avoided. Increment a only once per statement and do instead something like:
    Code:
    int b1=a++;
    int b2=++a;
    b=b1+b2;
    int b3=a++;
    int b4=++a;
    printf("%d,%d,%d,%d",b,b3,a,b4);
    
    for defined behaviour on all platforms and compilers.
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice