Reference vs. copy in a range-based for loop
Understanding the difference between using a reference or a copy of a value is critically important in C++. By default, when we pass a value to a function, it is passed by values, which means we pass a copy of it. The same applied to a for loop/
This is an example of using a range-for loop for incrementing and printing values of an array (or any other container). There are two functions here, one which increments the copied values and the other which increments the original values. Understanding the difference between these two is the key.
int arr[]{ 1,2,3,4,5,6,7,8,9,10 };
void by_val()
{
for (auto i : arr) cout << ++i; //incremented copy
cout << endl;
for (auto i : arr) cout << i; //printing ORIGINAL values!!
}
void by_ref() { for (auto &i : arr) cout << ++i; //incremeted original cout << endl; for (auto &i : arr) cout << i; //printing incremented values
}
When theses functions will be called, one will modify the values in the array and the other will not modify it at all. The first one will not modify the original array - we pass the values, the second one will modify - we pass by reference.
Simply put, if you want to change (increment, decrement, or do whatever else with) the original value, you have to use a reference (put & in front of the variable).
So the first range-for statement that is inside of the function print() says: “for each element of arr, from first to last, put a copy of it into the variable 'i' (and do whatever with that copy..)”, while the second range-for inside of the function increment() says: “refer to each element of arr, from first to last, and use its value”.
Reference is similar to pointer except that you don´t need to use the * prefix to access and use its value. Another difference is that reference cannot refer to a different object after it is initialized, a pointer can.