Jing S. answered 10/04/19
M. S. in Computer Science with more than twenty years experience
First, let's look at an simple example:
=====================
#include <iostream>
using namespace std;
void add_by_value(int a)
{
a = a + 5;
}
void add_by_ref(int &a)
{
a = a + 5;
}
int main(int argc, char *argv[])
{
int a = 5;
cout << "Initial: " << a << endl;
add_by_value(a);
cout << "add_by_value: " << a << endl;
add_by_ref(a);
cout << "add_by_ref: " << a << endl;
}
======================
Run the code above, we get
Initial: 5
add_by_value: 5
add_by_ref: 10
Why do we have the result above?
- Pass by value means a copy of the a is passed to add_by_value function. So while a is incremented in the function, it does not change the original variable a's value
- Pass by reference means a reference pointer is passed to add_by_ref function. SO the addition is done on the original variable a. So the value is changed to 10.
I hope this explanation helps you to understand this concept.