Code:
#include <iostream>
using std::cout;
using std::endl;
void ByRef(int& x){
x *= 10;
cout << "x in ByRef() = " << x << endl;
}
void ByVal(int x){
x *= 10;
cout << "x in ByVal() = " << x << endl;
}
int main(){
int x = 10;
cout << "Before ByVal() x = " << x << endl;
ByVal(x);
cout << "After ByVal() x = " << x << endl;
cout << "**x has not changed in the main function**" << endl;
ByRef(x);
cout << "After ByRef() x = " << x << endl;
cout << "**This time x has changed**" << endl;
return 0;
}
Notice here that the two functions are almost identical and are used the same, but ByRef() recieves the int as a reference.
What this means is that the passed value is passed by reference, and so any changes to the value in ByRef() are reflected by the same changes to the value in the main function.
With ByVal(), a copy of the int is sent, and so any changes made to it are not reflected in the value held in the main function.
Passing by reference can be troublesome as it can screw up the variable unintentionally. To combat this if you dont want the value changed, you would declare the recieved value in the function to be constant with the "const" keyword.
You may wonder why bother sending by reference at all.....the benefit is that with send by reference, the recieved value is an alias for the sent value and so therefore is more efficient as a whole value does not need to be passed. (this is here nor there for an int, but does matter with large objects).
Hope that helps