Please explain code

Hi, I'm having a hard time as to understand why the answer for b is 4 and for c is 3. Any clarifying comments will be highly appreciated.




#include <iostream>

using namespace std;
int fun1(int p){
++p;
return p++;
}

int fun2(int &p) {
++p;
return p++;}


int main()
{
int a = 1, b , c;
b = fun1(a);
c = fun2 (b);
cout << a << endl;
cout << b << endl;
cout << c << endl;


return 0;
}

sigh. what an excellent way to spend a student's time...

its trying to teach you that ++p vs p++ are different. its order of operations...

int p = 1;
cout << p++; //writes 1, then increments p to 2.
cout << p; << 2
cout << ++p; //increments, then writes: writes 3
cout << p; still 3

right?

this is coupled with teaching you about pass by reference vs pass by value. By mixing the two concepts they made it difficult to understand either one of them (this is my complaint with this exercise). With the above, can you see how the pass by references vs value are different and that the order of operations from pre/post increments is playing off that to give the values you see?

I can break it down more, but see if you can unravel it first... give it another try.


Last edited on
Thanks jonnin (1956). Still sigh, I'm afraid. I'm struggling to see how invoking only fun1 for the calculation of b can result in b = 4.
ok.

b = fun1(a);
a is 1,
fun1 increments twice,
b = 2, correct?

now
c = fun2 (b);
but b is passed by references. changes to 'p' in fun2 affect b:
fun 2 increments 'p' twice, but p IS b, so b is incremented twice more.
b = 4.

so the answer is that you did not 'only' call fun1 on b. You called fun2 on b also!
Last edited on
Ah, thanks jonnin (1964), for shedding some light here. All the best.
Topic archived. No new replies allowed.