Just a minor nitpick. Arrays are
not passed by-reference, they're passed by-pointer (which is a subtle yet very important difference when it comes to understanding what your compiler is doing, and what information it has available inside the function body).
You'll see the difference most clearly whenever you try to do something like figure out the sizeof an array passed by-pointer.
If you want to truly pass an array by-reference (and not by-pointer), you need to think about C++'s "right-left" parsing rule. i.e.
int (& foo)[10]
means '
foo' ... '
is a reference to' ... '
an array of 10' ... '
int'
If you used
int (& foo)[10]
as a function argument, then sizeof(foo) would be equal to
10 * sizeof( int )
However if your function looked like
void func(int foo[10])
then sizeof(foo) would be equal to
sizeof( int* )
The difference between these - by-reference means the function knows how long the array is, by-pointer means that it hasn't got a clue (in the C language, people only have pass-by-pointer available, and often drop in a separate "size" argument alongside the array to use for bounds-checking)
passing an array by-reference can be helpful when mixed with templates - you can let your compiler work out how big your array is for free
1 2 3 4 5 6 7 8 9 10 11
|
template< int N >
int HowLongIsMyArray( double (& foo)[N] )
{
return N;
}
int main()
{
double foo[10];
std::cout << "My array is " << HowLongIsMyArray( foo ) << " elements long" << std::endl;
}
| |
That trick wouldn't work without the additional (and sadly ugly) reference syntax (And doesn't work with pointers either)