Consider the following code fragment void foo(int x, int y) { x+=y; y+=x; }…
2015
Consider the following code fragment
void foo(int x, int y)
{
x+=y;
y+=x;
}
main()
{
int x=5.5;
foo(x,x);
}
What is the final value of x in both call by value and call by reference, respectively?
- A.
5 and 16
- B.
5 and 12
- C.
5 and 20
- D.
12 and 20
Attempted by 328 students.
Show answer & explanation
Correct answer: C
The variable x is declared as int, so assigning 5.5 truncates it to 5.
In Call-by-Value, parameters are copies. Modifications inside foo do not affect the original x in main. Final value: 5.
In Call-by-Reference, parameters refer to the original variable. Both x and y point to the same memory location. First operation: x += y (5 + 5 = 10). Second operation: y += x (10 + 10 = 20). Final value: 20.