What is the output of the following C++ program?
#include<iostream>
using namespace std;
void modify (int &a, int b) {
a = a + b;
b = a - b;
}
int main() {
int x = 5, y = 10;
modify (x, y);
modify (x, y);
cout << "x=" << x << y << endl;
}
Explanation
This problem tests your understanding of pass-by-reference (int &a) versus pass-by-value (int b) in C++.
1. Initial State:
x=5,y=10
2. First call: modify(x, y)
a is a reference to x (changes to a affect x).
b is a copy of y (changes to b do not affect y).
Operation:
a = a + b ⟹a=5+10=15. Since a refers to x, now x=15.
b = a - b ⟹b=15−10=5. Since b is local, y remains 10.
After first call: x=15,y=10.
3. Second call: modify(x, y)
Use current values: x=15,y=10.
Operation:
After second call: x=25,y=10.
Conclusion:
The program outputs x=25 followed by the value of y (which is 10). Therefore, the output is x=25 y=10.
The correct option is (d).