Tuesday, June 07, 2005

C++ reference to an array

A number of years ago I remember learning how to pass a reference to an array of fixed size to a function in C++. The C++ Primer by Stan Lippman and Josee Lajoie discuss how to do this in section 7.3 (Functions - Argument Passing). It looks like this:

void foo(int (&refArr)[10])
{
size_t size = sizeof(refArr); // returns 10*sizeof(int)
}


Today Jonathan asked how to return a reference to an array of fixed size. I took a quick look at the spec and saw that returning a reference to an array is allowed, but I couldn't find how.

Well, it turns out that is looks like this:

const int (&getArray() const)[10]
{
return array_;
}


Fun!