explain code Please

Feb 13, 2018 at 12:22pm
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.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #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;
}
Last edited on Feb 13, 2018 at 12:25pm
Feb 13, 2018 at 12:50pm
Okay. So let's start with functions explanation.

fun1 gets int argument by value, so there is local copy of p. First preincrement just add 1 to it and the second one is postincrement so returned value will not change.

fun2 gets int argument by reference, so inside this function you are working with real varialbe declared outside not a local copy of it. So returned value will be incremented by 1 same way, but postincrement in return statement will add one more 1 to referenced variable.

For initial a = 1, b and c have random values;

b = fun1(a); - a won't changed (see fun1 description), and b will be a + 1 = 2;
c = fun2(b); - b will be b + 2 = 2 + 2 = 4 (see fun2 description), and c will be 2 + 1 = 3;

These results you can see with cout.
Last edited on Feb 13, 2018 at 12:51pm
Topic archived. No new replies allowed.