Pass-by-reference parameters:
Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. C onlyIn C, the corresponding parameter in the called function must be declared as a pointer type. C++ only In C++, the corresponding parameter can be declared as any reference type, not just a pointer type.
The following function swap uses reference parameters:
void swap(int& a,int& b)
{
int temp = a;
a = b;
b = emp;
}
Now, swap does have an effect on the arguments in the caller - as it must to be of any use. Thus:
float x=10, y=20, z=0;
swap(x, y);
cout<< x<<", "<< y<< endl;
will result in 20, 10
Notice that the caller need not make any special indication of the reference nature of the arguments - that is all handled by the definition of the function: int& a,int& b.
Thus, void swap(int& a,int& b)
Just to drive the point home, let us examine a naive swap which uses pass-by-value.
void swapSilly(int a,int b) //naive -- pass by value
{
int temp=a;
a=b;
b=temp;
}
Now, swap Silly does NOT have an effect on the arguments in the caller, hence the function has no effect. Thus:
float x=10, y=20, z=0;
swapSilly(x, y);
printf ("%d , %d \n",x,y);
will result in 10, 20
Example program:
1. Swap two numbers