Passing an array by reference
Solution 1:
It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
EDIT: Some clarification.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
This is parsed as an "array of references" - which isn't legal.
Solution 2:
It's just the required syntax:
void Func(int (&myArray)[100])
^ Pass array of 100 int
by reference the parameters name is myArray
;
void Func(int* myArray)
^ Pass an array. Array decays to a pointer. Thus you lose size information.
void Func(int (*myFunc)(double))
^ Pass a function pointer. The function returns an int
and takes a double
. The parameter name is myFunc
.
Solution 3:
It is a syntax. In the function arguments int (&myArray)[100]
parenthesis that enclose the &myArray
are necessary. if you don't use them, you will be passing an array of references
and that is because the subscript operator []
has higher precedence over the & operator
.
E.g. int &myArray[100] // array of references
So, by using type construction ()
you tell the compiler that you want a reference to an array of 100 integers.
E.g int (&myArray)[100] // reference of an array of 100 ints