pointer and functions
Comparison between call by value and call by reference
A function may be invoked in two ways
(a) Call by value
(b) Call by reference
Call by value:
Incall by value if we modify the values of the arguments passed to the called function within the called function then those modifications are visible only within the called function they are not be visible in the calling function.
Example of call by value
//call byvalue #include<iostream> #include<conio.h> using namespace std; void abc(int n) { n=100; } int main() { int a=10; cout<<"a= "<<a<<endl; abc(a); cout<<"a= "<<a<<endl; getch(); return(0); }
Output:
a= 10
a= 10
Call by reference:
This method can itself be used in two ways:
(i). Bypassing the pointers
(ii). Bypassing the reference
Bypassing the pointers
When the pointers are passed to the function , the address of the actual arguments in the calling function are copied into the formal arguments of the called function. This means using the formal arguments ( the address of the original values) in the called function , we can make changes in the actual arguments of the calling function.
Therefore in this method the called function does not create its own copies of the original values rather it refers to the original values by the addresses (passed through pointers) it receives.
Example of passing by pointers
//call byvalue #include<iostream> #include<conio.h> using namespace std; void abc(int *n) { *n=100; } int main() { int a=10; cout<<"a= "<<a<<endl; abc(&a); cout<<"a= "<<a<<endl; getch(); return(0); }
Output:
a= 10
a= 100
Bypassing the reference
When parameters are passed to the function by reference, then the formal parameters become references (or aliases) to the actual parameters in the calling function. This means that (in this method) the called function does not create its own copies of original values, rather it works/refers to the original values by different names i.e. their references. Thus the called function works with the original data and any changes in the values gets reflected to the data in the calling function.
The call by reference method is useful in the situations where the values of the original variables are to be changed using a function.
• By using call by reference we can modify any number of values without actually returning any values because in call by reference we make modifications at the very locations where we want to change the values.
• Functions have a limitation that they can return a maximum of one value; this limitation can be overcome by using call by reference.
Example of passing by reference
//call byvalue #include<iostream> #include<conio.h> using namespace std; void abc(int &n) { n=100; } int main() { int a=10; cout<<"a= "<<a<<endl; abc(a); cout<<"a= "<<a<<endl; getch(); return(0); }
Output:
a= 10
a= 100