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

post & pre increment question - very confusing

Discussion in 'C' started by tedman, Jan 28, 2007.

  1. tedman

    tedman New Member

    Joined:
    Jan 28, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Please help me with this, I am having a hard time!!!
    Code:
        main()
        {
            int x=10, y=15;
            x = x++;
            y = ++y;
            printf(ā€œ%d, %d\nā€,x,y);
    
        }
    the result for the above is 10, 16 , if i replace x=x++ with x++ the result is 11,16
    so isnt x=x++ and x++ same??

    secondly
    Code:
        main()
        {
            int x=20,y=35;
            x=y++ + x++;
            y= ++y + ++x;
            printf(ā€œ%d%d\nā€,x,y);
    
        }
    the answer is 57, 94 on a mingw32-gcc.exe compiler and 56, 93 on a gcc compiler!!! so do different compilers work differently??

    Thanks guys
     
    Last edited by a moderator: Jan 29, 2007
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    First, read "Before you make a query". If you already have, then you're just being rude.

    Secondly, the operations you're performing result in undefined operation. The compiler can do anything it likes, including melt your system into a slag heap. Read about sequence points.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    x = x++;
    You are assigning the value to the variable and then incrementing it and so it is 10
    y = ++y;
    You are incrementing the value and then assigning it and so its one more than the original value.
    x=y++ + x++;
    y= ++y + ++x;
    For this try evaluating from Right to left because C is normally Right To Left evaluated and almost all the compilers follow that but as DaWei said you are at the mercy of the compiler to give you results.
     

Share This Page