we have seen before that parameter are mentioned in the function definition and they are used to hold the values that are sent by the calling function. so Any changes make to the parameters inside the function do not effect the actual arguments. This mechanism of the passing arguments is called call by value. and other mechanism where arguments passed can be change by changing parameters is called call by reference using pointer. When we pass value from calling function to called function or function a defination it is known as call by value
Function prototype is a declaration statement in the calling program and in the following form
/* program to understand the call by value */
#include <iostream>
void sum(int x,int y);
int main()
{
int a,b;
std::cout<<"Enter the value of a \n";
std::cin>>a;
std::cout<<"Enter the value of b \n";
std::cin>>b;
sum(a,b);
return 0;
}
void sum(int x,int y)
{
int sum;
sum=x+y;
std::cout <<"\nSum of a and b="<<sum;
}
call By Reference
The call by reference is a method of passing arguments to a function copies the address of argument into the formal parameter. Inside function the address is used to access the actual arguments or the value of actual arguments in the calling. That means changes made to the original variables.To pass a value by reference,argument pointers are passed to the called function just like any other value. lets take the example to understand call by reference
/* program to understant the call by reference */
#include <iostream>
void swapn( int *num1, int *num2 )
{
int temp ;
temp = *num1 ;
*num1 = *num2 ;
*num2 = temp ;
}
int main( )
{
int n1 = 50, n2 = 30 ;
std::cout<<"Before swapping:";
std::cout<<"\n n1 is"<<n1;
std::cout<<"\n n2 is"<<n2;
/*calling swap function*/
swapn( &n1, &n2 );
std::cout <<"\n After swapping:";
std::cout <<"\n n1 is" <<n1;
std::cout <<"\n n2 is" <<n2;
return 0;
}