While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.
Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function. Thus the variables in the calling function remain unchanged.
Example:
void printFunc(int a,int b,int c)
{
a *=2;
b *=2;
c *=2;
}
int main()
{
int x = 1,y=3,z=4;
printFunc(x,y,z);
cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}
Output:
x=1
y=3
z=4
As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.
However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.
To demonstrate this we modify the above program as follows:
void printFunc(int& a,int& b,int& c)
{
a *=2;
b *=2;
c *=2;
}
int main()
{
int x = 1,y=3,z=4;
printFunc(x,y,z);
cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}
Output:
x=2
y=6
z=8
As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique. This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself.