lets look at an example function:
Code:
int isEven(int x)
{
if ( x % 2 == 0 )
return 1;
else
return 0;
}
this function returns 1/true if the given number number is even, and 0/false otherwise. what if some program we are using expects all numbers it uses to be even? we can modify this function so that if the given number is odd, we can make it even, and "return" that new even number as well as whether the original number was even or odd (say our program has a counter of how many "original" numbers were actually even vs. odd; i know silly).
we can change our function to use pass by reference:
Code:
int isEven(int &x)
{
if ( x % 2 == 0 )
return 1;
else
{
// x is odd, so lets make it even
x++;
// x is now even
// the important thing is that since x was passed by reference, the original variable is also changed, i.e. the one in the "int main()" function or
// whoever else called this function.
// this is important because, in our example, the program/main() expects to only work with even numbers.
return 0; // however we still need to return 0/false/"odd number" to the calling function who is keeping a count of how many even vs. odd
}
}
again, somewhat of a silly program i know, but i hope it helps you understand. when this function is called, the actual variable is not passed from the calling function, but a pointer to the memory address of where the variable is. because of this, any changes made to the variable (via the pointer) in the isEven function, effect the original variable (since it is modifying the same memory address).