## Tuesday, November 15, 2011

### C++ Tutorial: Passing arguments by reference and returning by reference.

Pass by Reference
Pass by reference in C++ is implemented as the variable aliasing. The function definition for pass by reference is defined as follow:
void incr(int &num)
{
num++;
}

The call to this function is
incr(a);
The call to this function creates alias of the passed argument a as num. Since num is the alias of any passed arguments, the passed argument is changed in the function. This function increases the variable passed as arguments in the calling function. This function increases the variable passed as arguments in the calling function.

Return by Reference
In C++, a function can be return a variable by reference. Like the variable alias in passing arguments as reference the return by reference returns the alias (actually the reference which does not need the dereferencing operator). It allows the function to be written on the left hand side of the equality expression. Using C style of returning the address, the function should return the address of the variable as:
int *max(int *n1, int *n2)
{
if(*n1 > *n2)
return n1;
else
return n2;
}

The function is called as
*max(&a1, &a2) = 100;
The return by reference is simplified in C++ by using the alias mechanism. The function definition for return by reference is of the following form in C++
int &max(int &n1, int &n2)
{
if(n1 > n2)
return n1;
else
return n2;
}
It is called as
max(a,b) = 100;
This example return the reference of the variables that are passed as reference to the function.