Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include<iostream>
    using namespace std;

    void sum(int a,int b,int &c)
    {
        c = a++ + b++;
    }
    int main()
    {
        int a = 10, b= 20,c;

        sum(a,b,c);
        cout<<a<<"  "<<b<<" "<<c<<endl;
        return 0;
    }


What I have tried:

value of c should have been assigned as 33 but instead it's just 30
Please help to understand this
Posted
Updated 19-Aug-19 15:52pm

There'a a bunch of issues here, but the answer being wrong is because those postfix ++ operators are executed AFTER the + expression is evaluated in your sum method.

So it's adding 10 and 20 together and setting the result to 30, THEN it increments the values of a and b. But, since a and b are passed "by value" and not "by reference" like c is, the values of a and b in your main method will always be 10 and 20.
 
Share this answer
 
Quote:
value of c should have been assigned as 33 but instead it's just 30

30 is, the correct result for this code!
Your code means:
C++
void sum(int a,int b,int &c)
{
    //c = a++ + b++;
    c = a + b; // 30 is the correct result!
    a = a + 1;
    b = b + 1;
}

which is post increment.
If you use pre increment, the correct result is 32:
C++
void sum(int a,int b,int &c)
{
    //c = ++a + ++b;
    a = a + 1;
    b = b + 1;
    c = a + b; // 32 is the correct result!
}
 
Share this answer
 
Have a look here: Why does x = ++x + x++ give me the wrong answer?[^] - it explains what is happening, even if you aren't doing really silly things with pre- and post- increment.
 
Share this answer
 
Try:

c = (a++) + (b++);

I think.
 
Share this answer
 
Comments
Richard MacCutchan 20-Aug-19 3:57am    
Try it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900