In: Computer Science
(a) Discuss how an actual parameter is related to its
corresponding formal parameter in the following four
parameter-passing
methods for procedure calls.
a. Pass by value
b. Pass by reference
c. Pass by name
(b) Given the output of the following program (written in C syntax)
using the above three parameter-passing methods:
int i, j, a[5]; // a is a 5 element array with indices 0 - 4
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
for (j=0; j<5; j++)
a[j] = j;
i = 1;
swap(i, a[i+1]);
printf("%d %d\n", i, a[2]);
return 0;
}
Assume that procedure arguments are evaluated from left to right.
What numbers does the program print if both parameters
in swap are passed by
a. value?
b. Reference?
c. Name?
Note that you can get partial credit if you show your hand
evaluation of the code.
( a ) an actual parameter is related to its corresponding formal parameter
a . Pass by value
The changes made to formal parameter does not get transmitted back to the calling function. Any changes made to the formal parameter variable inside the called function will not be reflected in the actual parameter in the calling function or method.
b . Pass by reference
The changes made to formal parameter does get transmitted back to the caller function . Any changes made to the formal parameter are reflected in the actual parameter in the calling function.
This is done because formal parameter receives a reference to the actual data and passed to the function.
c. Pass by name
In this parameter passing, symbolic “name” of a variable is passed to the calling function, which allow to be access and update in the same function.
( b )
int i, j, a[5]; // a is a 5 element array with indices 0 -
4
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
for (j=0; j<5; j++)
a[j] = j;
i = 1;
swap(i, a[i+1]);
printf("%d %d\n", i, a[2]);
return 0;
}
The program print if both parameters in swap are passed by :
a) Value :
OUTPUT is : 1 2
b) Reference :
OUTPUT is : 2 1
c ) Name :
OUTPUT is : 2 1