An example of passing by value and reference
In the following example, we examine passing by value via a pointer, passing by reference including a pointer to a pointer and const reference.
Code:int f(int* pi, int **ppi, int& ri, const int& cri)
{
int i1 = *pi + 1;
//original poinetr modified in the function, but the integer pointed to will not change on return
pi = &i1;
//the integer pointed to will change on return
//*pi = i1;
int i2 = **ppi + 1;
int* pi2 = &i2;
//ppi = &pi2;
//instead do this to modify the pointer
*ppi = pi2 + 1;
int i3 = ri + 1;
ri = i3;
int i4 = cri + 1;
//cannot compile because you cannot change const by reference
//cri = i4;
return i1 + i2 + i3 + i4;
}
Code:int main()
{
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
int* pi2 = &i2;
int n = f(&i1, &pi2, i3, i4);
return 0;
}
Code:
i1 i2 i3 i4
start 1 2 3 4
return 1 x 4 4
As we discussed
here, when a pointer is passed to a function, it is passed by value. So i1 is passed by value not reference. Even though the function f modified the local pointer, the original pointer is not affected. i2 is passed via a pointer to a pointer (ie. by reference), the original pointer is modified in the function call. Unlike i1 which is passed by a pointer, i3 is passed by reference and the original value is changed in the function call. i4 is passed by const reference so we cannot change the original value.