Both functions permit modification of array within the functions. Are these two forms of array passing equivalent? What (if any) advantage is gained by passing the array by reference, as in function2?
What (if any) advantage is gained by passing the array by reference, as in function2?
Very little. About the only benefit is that you are guaranteed that the array is exactly of size n, whereas when you pass by pointer, the array could be of any size.
void byptr(int*);
void byref(int (&r)[5]);
int main()
{
//an array of 5 elements
int five[5];
byptr(five); // OK
byref(five); // OK
// an array of 4 elements
int four[4];
byptr(four); // OK
byref(four); // ERROR, int[4] is not int[5]
// an array of 6 elements
int six[6];
byptr(six); // OK
byref(six); // ERROR, int[6] is not int[5]
// dynamic array of any size
int* dyn = newint[5];
byptr(dyn); // OK
byref(dyn); // ERROR, int* is not int[5]
}
Really, just about the only thing passing an array by reference is good for is for the templated arraysize function:
1 2 3 4 5 6 7 8 9 10 11 12
template <typename T,unsigned S>
inlineunsigned arraysize(const T (&v)[S])
{
return S;
}
int main()
{
int foo[] = {1,2,3,4,5};
cout << arraysize(foo); // prints 5
}