I have the following code in C++:
#include <iostream>
using namespace std;
int x;
void p(int a, int &b) {
cout << x << " " << a << " " << b << endl;
if (a < b) {
a = x+b;
}
else {
--x;
b += a;
a = x/2;
cout << x << " " << a << " " << b << endl;
p(b-x, a);
}
cout << x << " " << a << " " << b << endl;
}
int main() {
x = 17;
p(42, x);
cout << x << endl;
}
The output of this code is the following, which I don’t understand:
17 42 17
58 29 58
58 0 29
58 87 29
58 29 58
58
Specifically, in main, x=17 assigns a global parameter. It starts calculating p(a=42,&b=17). It prints out: x = 17 (global),a = 42 ,b = 17 (pointer). Good so far!
Next, it goes to if. if 42<17 is not satisfied and goes to else, in which x is decremented by one so x=17-1=16. Not 58.
What is going on? Can someone please explain?
>Solution :
Your parameter b is a reference (ie, alias) to an int variable. In this case, it refers to the global variable x, since that is what main() is passing in. So, x and b are separate names for the same memory block that is holding an int value. As such, anything you do to x is reflected in b and vice versa.
When your code goes to the else for the 1st time, the value of x (and thus b) is 17. You decrement x (and thus b) by 1, and then increment b (and thus x) by a (42). So, you are actually incrementing x by 41, hence why x becomes 58 (17-1+42=58).