pass by value takes a copy of the variable's value and manipulates it. No matter what happens to the copied value the original value remains unchanged. When the variable is passed by reference it is the original that is being manipulated which may change the original value to something else.
here's an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void f(int,int&);//proto
int main()
{//tests the f()function
int a=22,b=44;
cout<<"a = "<<a<<" , b = "<<b<<endl;//prints a=22, b=44
f(a,b);
cout<<"a = "<<a<<" , b = "<<b<<endl;//prints a==22, b=99
f(2*a-3,b);
cout<<"a = "<<a<<" , b = "<<b<<endl;//prints a=22, b=99
}
void f(int x,int&y)
{//changes reference arguement to 99
x=88;
y=99;
}
|
Here is something from a book 1:
passing by value
int x;
-the parameter x is a local variable
-it is a duplicate of the argument
-it cannot change the argument
-the argument passed by value may be a constant,
a variable or an expression
-the argument is read-only
passing by reference
int &x
-the parameter x is a local reference
-it is a synonym for the argument
-it can change the argument
-the argument passed by reference must be a variable
-the argument is read-write
1 Programming with C++ John R Hubbard,Ph.D.