The question is incomplete! Complete question along with its step by step answer is provided below!
Question:
Given the following function definition:
void calc (int a, int& b)
{
int c;
c = a + 2;
a = a * 3;
b = c + a;
}
x = 1;
y = 2;
z = 3;
calc(x, y);
cout << x << " " << y << " " << z << endl;
What is the output of the following code fragment that invokes calc?
a. 1 2 3
b. 1 6 3
c. 3 6 3
d. 1 14 9
e. None of these
Answer:
b. 1 6 3
Explanation:
In the given problem we have a function void calc which takes two input arguments a and b and updates its values according to following equations
c = a + 2;
a = a * 3;
b = c + a;
Then we call this function calc(x,y) by providing test values of
int x = 1;
int y = 2;
int z = 3;
and the output returns the values of x, y and z
cout << x << " " << y << " " << z << endl;
Lets find out what is happening here!
When the program runs we provide x=a=1 and y=b=2
c=a+2=1+2=3
a=a*3=1*3=3
b=c+a=3+3=6
So the updated values of a=x=3 and b=y=6?
NO!
The updated values are a=x=1 and b=y=6
WHY?
There are two ways to pass values
1. Pass by values -> value cannot change (int a)
2. Pass by reference -> value can change (int& b)
Look at the function void calc (int a, int& b)
;
Here we are passing (int a) as a value and (int& b) as a reference, therefore x remains same x=1 and y gets changed to updated value y=6 and z remains same as z=3 since it wasnt used by function calc(x,y)
The right answer is:
b. 1 6 3
x=1, y=6, z=3