Pass By Reference
In pass by reference method, the function will operate on the original variable itself. It doesn't work on a copy of the argument but works on the argument itself.
Consider the same square function example I took in the previous section.
// Illustration of pass by reference
void square (int *x)
{
*x = (*x) * (*x);
}
int main ( )
{
int a = 10;
square(&a);
cout<<" Value of a is "<<a;
// Value of a is 100
return 0;
}
As you
can see the result will be that the value of a is
100. The idea is simple : the argument passed is the address of a.
The parameter of square is a pointer pointing to
type integer. The address of a is assigned to this
pointer. Within the function I've written :
*x = (*x) * (*x);
* when used before a pointer, will give the value stored at that particular
address. Hence we find the product of a and store
it in a itself. i.e. the value of 100 is stored in the address of a
instead of 10 which was originally stored.
This is a call-by-reference method which was used in C. In C++ there is a different approach. Of course you can use the above method, but C++ has its own way.
Go to the next section : Pass By Reference C++ style
or Go back to Contents page 2.