In: Computer Science
void swap(int a, int b) { int temp; temp = a; a = b; b = temp;}
void main() {
int value = 2, list[5] = {1, 3, 5, 7, 9};
swap(value, list[0]);
swap(list[0], list[1]);
swap(value, list[value]);
}
For each of the following parameter-passing methods, what are all of the values of the variables value and list after each of the three calls to swap?
Passed by value
In passed by value method only the copys of actual variables are passed as parametrs.Which means whatever changes are happened to parameters in swap function it will not reflect on the actual variables
so in our program,
There will be no change for 'value' and 'list' after exexution of the program.Becouse whenever we call swap using pass by value method we are jsut passing a copy of it
so Lets check the changes after each line of execution
at beginning : value= 2 ,list = {1, 3, 5, 7, 9}
swap(value, list[0]);
value= 2 ,list = {1, 3, 5, 7, 9}
swap(list[0], list[1]);
value= 2 ,list = {1, 3, 5, 7, 9}
swap(value, list[value]);
value= 2 ,list = {1, 3, 5, 7, 9} //no change
Passed by reference
In passed by reference method ,reference to the actual variable is being passed .So for every change in the formal parameters in swap function will reflect on the actual variables in the main functions. Actually we are passing a reference to the actual variable into the swap function.so that the swap function can change the variable in main() using that reference
Lets check the changes after each line of execution
At beginning:
value = 2, list = {1, 3, 5, 7, 9}
swap(value, list[0]);
value = 1, list = {2, 3, 5, 7, 9}
swap(list[0], list[1]);
value = 2, list = {3, 2, 5, 7, 9}
swap(value, list[value]);
value = 5, list = {1, 3, 2, 7, 9}
Passed by value-result
This method of parameter passing is similar to pass by referenece ,but instead of changing the actual variables at every execution this method will change the actual variable only once when the function ends.Which means the sawp function will change the value of actual variable at end of the swap function only
But this method have no effect in our program, it will be same as pass by reference method shown above
(This methods have effects in functions in which values of formal variables changed several times in called function)
So lets check the changes at every line of execution
At beginning:
value = 2, list = {1, 3, 5, 7, 9}
swap(value, list[0]);
value = 1, list = {2, 3, 5, 7, 9}
swap(list[0], list[1]);
value = 2, list = {3, 2, 5, 7, 9}
swap(value, list[value]);
value = 5, list = {1, 3, 2, 7, 9}