//x is copied to a new variable
//so changes to this x dont affect the original x
void modify_value(int x)
{
x = x + 1;
}
//reference to the original x
//changes to this x affect the original x because a reference and a variable are the same
void modify_ref(int &x)
{
x = x + 1;
}
int main()
{
int x = 3;
int &ref_x = x;
modify_value(x);
cout << x << endl; //x = 3
modify_ref(ref_x);
cout << x << endl; //x = 4
}
You may have noticed similarity with pointers.
1 2 3 4 5
//changes to this x affect the original x.
void modify_pointer(int *x)
{
*x = *x + 1;
}
An advantage of references over pointers is safety.
A reference would always be initialized before being used or passed to a function.
That is not the case with a pointer as modify_pointer(NULL) is valid;
From their definition as another name to a variable they seem totally useless.
They are quite useless when used locally in the same function as the referenced variable is defined. References are mostly useful when passing and returning from functions.