Let f be the following function, written in an imaginary language: void f(int j,
ID: 3769517 • Letter: L
Question
Let f be the following function, written in an imaginary language:
void f(int j, int k) {
j++;
i--;
k = i + 2;
}
Assume that i is global to this function and that a is an array of integers.
Now, suppose that the following statements are executed:
i = 1;
a[1] = 5;
f(i, a[i]);
For each of the following sets of assumptions, indicate what the values of i and a[1] will be after the call of f.
(a) j and k are passed by reference.
(b) j and k are passed by value-result.
(c) j is passed by reference and k is passed by name.
(d) j is passed by value-result and k is passed by name.
Explanation / Answer
(a) j and k are passed by reference.
In this method, j refers to the location where i resides.
k points to the location where a[1] is resides.
if *j++ is executed, then the value present in it incremented.
As a result , i becomes 2.
value of i =2.
If i-- is executed, again i becomes 1.
If *k=i+2 is executed, value in k becomes 1+2=> 3, as a result
value of a[1] becomes 3.
So when we print ans:
i=1 and a[i]=3
--------------------------------------------------------------------
(b) j and k are passed by value-result.
In this method, j get the value of i
k points get the value of a[1].
if j++ is executed, then the value of j is incremented.
As a result , j becomes 2.
value of i is 1.
If i-- is executed, it becomes 0. (since i is global)
If k=i+2 is executed, value of k becomes 0+2=> 2.
Here just the value of j an k are get modified. Since they
didnt refers to the actual location of the i and a[i],
value of i and a[i] will not get modified
So when we print answer:
i= 0 and a[1]=5
-----------------------------------------------------
(c) j is passed by reference and k is passed by name.
answer Similar to case b.
-------------------------------------------------
(d) j is passed by value-result and k is passed by name.
In this method, j get the value of i
k points get the value of a[1].
if j++ is executed, then the value of j is incremented.
As a result , j becomes 2.
value of i is 1.
If i-- is executed, it becomes 0. (since i is global)
If k=i+2 is executed, value of k becomes 0+2=> 2.
Here just the value of j an k are get modified. Since they
didnt refers to the actual location of the i and a[i],
value of i and a[i] will not get modified
So when we print answer:
i= 1 and a[1]=5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.