1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Postfix and prefix operator: why the value comes out as the same?

Discussion in 'C++' started by hbchen, Oct 15, 2007.

  1. hbchen

    hbchen New Member

    Joined:
    Oct 15, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    What is the value of "val" after for's first loop?
    A.
    for (int val = 1; val <= 10; ++val)
    {
    cout << val <<endl; //I expected 2, but the result was 1.
    }
    B.
    for (int val = 1; val <= 10; val++)//Result: 1
    {
    cout << val <<endl; //I expected 1, the result was 1.
    }
    Why got the same value?
    I looked at the explanation, but do not quite understand why the results came that way:
    " The postix increment operation occurs after the operand is evaluated.
    In the prefix form, the increment takes place before the value is used in expression evaluation, so the value of the expression is different from the value of the operand.
    See section 1.9.17 in the C++ standard for more information."
    source: http://msdn2.microsoft.com/en-us/library/dy3d35h8(VS.80).aspx

    Please give me the specific answer. Thanks!
     
  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:
    In this situation, pre- or post-increment doesn't matter. val isn't evaluated until after the incrementing statement. The breakdown of your loop looks like this:

    val = 1;
    LOOP:
    if (val > 10) EXIT FROM LOOP
    cout << val << endl; First time through, val is 1.
    val++; OR ++val;
    // val is now 2, either way. There is no evaluation taking place at this step.
    GOTO LOOP
    LOOPEXIT

    You would need to know which to use if you were evaluating val in that same sequence point. For instance,

    val = 1;
    if (val++ == 1) // this is true because the comparison is made BEFORE the increment.

    val = 1
    if (++val == 1) // this is false because the increment is made BEFORE the comparison.
     
  3. hbchen

    hbchen New Member

    Joined:
    Oct 15, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Thank you, DaWei! You've made it exceptionally clear!
     

Share This Page