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

pre increment & post increment

Discussion in 'C++' started by cindrilla, Nov 26, 2010.

  1. cindrilla

    cindrilla New Member

    Joined:
    Sep 26, 2010
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Location:
    hyderabad
    hi frinds pls let me know wht will be d mechanism of preincrement & post increment i have got the basic idea of these terms but when i had come to htis pariticular question im going wrong so y is it pls anyone can help me
    c=(++a)+(++a)+(a++)+(a++);
    then if i assume a=5
    then
    then i will get c as
    c=6+7+7+8
    which is equal to 28 but it is showing as 27 y so?
     
  2. ThorAsgard

    ThorAsgard New Member

    Joined:
    Feb 16, 2010
    Messages:
    9
    Likes Received:
    3
    Trophy Points:
    0
    Location:
    Somerset,UK

    Just tried this in Microsoft Visual Studio 2010 C++

    Code:
     
    #include <iostream>
    using namespace std;
     
    int main()
    {
    int a = 5;
    int c = 0;
    c = (++a)+(++a)+(a++)+(a++);
    cout << "Resulting value : " << c << endl;
    return 0;
    }
    
    And result 28
    :happy:
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Behaviour is undefined as the exact time the post increment is performed is not specified.

    In Visual Studio, c=(++a)+(++a)+(a++)+(a++); is equivalent to
    ++a; ++a; c=a+a+a+a; a++; a++;
    which would give the result 28.

    But other compilers (including other versions of Visual Studio) might differ, and it is perfectly OK for a compiler to interpret this code as
    c=++a (preincrement a from 5 to 6 then take the value: 6)
    + ++a (preincrement from 6 to 7 then take the value: 7)
    + a++ (take the value 7 then post increment a to 8)
    + a++ (take the value 8 then post increment a to 9)
    which would be equivalent to c=6+7+7+8, which is also 28.

    and there could be other interpretations, such as the one you use to get 27. So the answer to this is not to abuse pre- and post-increment operators in this way; do not use the same variable more than once in an expression if you are going to pre- or post-increment it.
     
  4. ichandu

    ichandu New Member

    Joined:
    Oct 19, 2010
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    The c variable is set as =0;
    then calculate you get 28.

    thanks.
     

Share This Page