Why pass arrays by reference?

The following two function prototypes correspond to passing an array to a function (1) by "value" (i.e., pointer) and (2) by reference parameter,.

void function1(double arr[],int n);
void function2(double (&arr)[n],int n);

where

double arr[n]={d1,d2,...,dn};

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?

Thanks in advance!
Are these two forms of array passing equivalent?


Almost, but not quite.

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.


Examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 = new int[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>
inline unsigned arraysize(const T (&v)[S])
{
  return S;
}

int main()
{
  int foo[] = {1,2,3,4,5};

  cout << arraysize(foo);  // prints 5
}
Very clear explanation, thank you.
Topic archived. No new replies allowed.