Given the function definition
void Twist( int a, int& b ) {
int c;
c = a + 2;
a = a * 3;
b = c + a;
}
what is the output of the following code fragment that invokes Twist? (All variables are of type int.)
r = 1; s = 2; t = 3;
Twist(t, s);
cout << r << “ “ << s << “ “ << t << endl;

Respuesta :

output of the following code fragment that invokes Twist is:

1 14 3

Explanation:

In the function Twist(),two parameters are passed. First is passed by value and second is passed by reference. If a variable is passed by value then any change made by the function will not affect the original value of that variable but when a variable is passed by reference then any change made by the function will change the original value of that variable. When Twist() function invokes with a=3 and b=2 then value of c=3+2 i.e c=5, a=3*3 i.e. a=9 (value of "a" was 3 earlier) and and b=c+a i.e b=5+9. Here only "b"is passed by reference for variable "s" then any change in it's value will be reflected in the "s". That will update the value of "s" to 14.