Consider:
#include <iostream>
using namespace std;
void Change(int arr[3]) {
for (int i = 0; i < 3; i++) {
arr[i] = 1;
}
}
int Test() {
int arr[3] = { 0, 0, 0 };
for (int i = 0; i < 3; i++) {
cout << arr[i] << endl;
}
Change(arr);
for (int i = 0; i < 3; i++) {
cout << arr[i] << endl;
}
return 0;
}
Since arrays are passed by default as a pointer to their first element and not copied, changing the value of an element of the array in a function effectively results in changing the value of that element of the array in the function caller, which is why the above code outputs
0
0
0
1
1
1
If this is the case, then why would anyone need to pass an array like the following?
void Change(int (&arr)[3])
I am aware that the parentheses are needed to make the argument a reference to an array instead of an array of references, but what do I gain?
const
or mutable reference tostd::vector
orstd::array
and you will gain both readability and robustness. – Medawarint (&arr)[3]
is worse. You can no longer passstd::array<int, 3>
to it, nor a part of a larger array. Passingstd::span<int, 3>
would work around that, but the benefits over a plain pointer are questionable. – Millspan
is probably the better option, since it checks the size if given an array, but at the same time can be given a subarray or a larger array, orstd::array
. – Mill