Both the code will give you the same output. But at the end of the for
loop, the values of array v
is different.
In the first, x
is just another copy of the items in the array v
. If you print again the value of the array v
then it will be the same.
In the second, x
is a reference of the given items in the array v
. This code is printing the value and then increasing it by 1. If you print again the value of array v
then all the elements in it are increased by 1.
Try the following code:
int v[] = {0,1,2,3,4,5};
cout << "Before :";
for(auto& x : v) {
cout << x << ", ";
++x;
}
cout << endl << "After: ";
for (auto x: v) {
cout << x << ", ";
}
You will get the following output:
Before: 0, 1, 2, 3, 4, 5,
After: 1, 2, 3, 4, 5, 6,
Basically, both of your code is having different values for the array v
at the end of the for
loop.