Call by value
The call by value method of passing arguments to a function copies the actual value of an argument in the formal parameter of the function.
In this case, the modifications carried out on the parameter within the function have no effect on the argument.
By default, C++ programming uses call by value to pass parameters.
Example:
void swap(int x, int y) { int temp; temp = x; // save value x x = y; // put y into x y = temp; // put temp into y return; }
Call by reference
Calling by reference method to pass arguments to a function copies an argument’s address in the formal parameter.
Within the function, the address is used to access the argument used in the call. It means that changes made to the parameter affect the passed argument.
Example:
void swap(int *x, int *y) { int temp; temp = *x; // save value at address x *x = *y; // put y into x *y = temp; // put temp into y return; }
Return by reference
In C++ Programming, you can pass values by reference, or you can return a value by reference.
Consider the following function:
int &max(int &x, int &y) { if (x>y) return x; else return y; }
The function return type above is int&, this means the function returns a reference to x or a reference to y and the function call can be displayed on the left side of the assignment instruction.
That is, the max(a,b) = -1 instruction is legal and assigns -1 to a if it is larger or -1 to b.