Call by Value vs. Call by Reference
0. OverView
This time we will discuss the basic concepts in C++: call by value/ reference. As we know, & is the to get the address of an object. Call by value is pass the value, while call by reference is pass the address.
1. Call by Value
A new copy is created and used inside the function. Any change of this copy will not affect the original object.
void f1(int i){ i++; }
2. Call by Reference
The original copy is used inside the function, which can have a different name. Any change inside the function will at the same time change the original object. There is only one object inside and outside the function.
void f2(int &i){ i++; }
In this situation, any attempt to change value of i will cause compile time error. i is read-only inside the function. The reason to do so is because call by value copy the object, which can be memory-wasting.
void f3(const int& i) { }
3. Complete Code:
#include<iostream>
using namespace std;
// void: this function not return anything
/*
call by value:
A new copy is created and used inside the function. Any change
of this copy will not affect the original object.
*/
void f1(int i){ i++; }
/*
call by ref:
The original copy is used inside the function, which can have a different name.
Any change inside the function will at the same time change the original obejct.
There is only one object inside and outside the function.
*/
void f2(int &i){ i++; }
// any attemp to change value of i will cause compile time error.
// i is read-only inside the function.
// the reason to do so is because call by value copys the object, which can be memory-wasting.
void f3(const int& i) { }
// when you pass the array, remeber to pass the size of the array.
void f4(int A[], int len){
// compiler will change it into
// f4(int * A, int size)
// when passing an arrau to a function, it always applies call by reference
for(int i = 0; i < len; i++ )
A[i]++;
}
// some pass by value and same pass by ref
void f5(int a, int &b){}
int main(){
/* Call/ Pass by values vs. Call/ Pass by reference */
int a = 10;
f1(a);
cout << a << endl; // 10
f2(a); //11
cout << a << endl;
// new feature, the same as:
// int A[5] = {1, 2, 3, 4, 5};
int A[5] {1, 2, 3, 4, 5};
f4(A, 5);
for(int i = 0; i < 5; i++)
cout << A[i] << " "; // 2 3 4 5 6
}