| 1. |
Explain function call using pass by reference technique with an example. |
|
Answer» Pass by reference is another way of passing parameters to the function. Pass by reference or call by reference is the method by which the addresses of the variables (actual arguments) are passed to the called function. The symbol is used to refer the addresses of the variables to the called function. The changes made to the formal parameter will change values in the actual arguments. For example: #include<iostream> void swap(int&x,int&y);//function declaration int main() { //local variable declaration: int a = 100; int b = 200; cout<<"Before swap,value of a:"<<a<<endl; cout<<"Before swap,value of b:"<<b<<endl; //calling a function to swap the values variable reference. swap(a,b); cout<<"After swap,value of a:"<<a<<endl; cout<<"After swap,value of b:"<<b<<endl; return 0; } void swap(int&x,int&y)//fuction definition to swap the values. { int temp; temp = x;/* save the at address x */ x = y;\*put y into x */ y = temp;/* put x into y */ return; } Before the function call, the values of a and b were 100 and 200 respectively. After the function, though no values are returned back to the main(), shows the value of a and b as 200 and 100 respectively. This is due to call by reference in which changes made in the formal argument will affect the values in the actual argument. |
|