General rules of passing/returning reference of array (not pointer) to/from a function?

If you want to return a reference to an array from a function, the declaration would look like this:

// an array
int global[10];

// function returning a reference to an array
int (&f())[10] {
   return global;
}

The declaration of a function returning a reference to an array looks the same as the declaration of a variable that is a reference to an array - only that the function name is followed by (), which may contain parameter declarations:

int (&variable)[1][2];
int (&functionA())[1][2];
int (&functionB(int param))[1][2];

Such declarations can be made much clearer by using a typedef:

typedef int array_t[10];

array_t& f() {
   return global;
}

If you want it to get really confusing, you can declare a function that takes a reference to an array and also returns such a reference:

template<int N, int M>
int (&f(int (&param)[M][N]))[M][N] {
   return param;
}

Pointers to arrays work the same, only that they use * instead of &.


With C++11's trailing return type syntax, you can also write:

auto foo () -> int (&)[3]
{
    static int some_array[3]; // doesn't have to be declared here
    return some_array; // return a reference to the array.
}

You cannot return an array from a function.

8.3.5/6:

Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.

EDIT: You'll love the syntax:

int (&bar()) [5] {
  static int x[5];
  return x;
}


int (* & bar()) [6][10] {
    static int x[6][10];
    static int (*y)[6][10] = &x;
    return y;
}
// Note - this returns a reference to a pointer to a 2d array, not exactly what you wanted.

As Erik mentioned, you can't return an array from a function. You can return a pointer or a reference, although the syntax is quite hairy:

// foo returns a pointer to an array 10 of int
int (*foo(float arg1, char arg2))[10] { ... }

// bar returns a reference to an array 10 of int
int (&foo(float arg1, char arg2))[10] { ... }

I'd strongly recommend making a typedef for the array type:

// IntArray10 is an alias for "array 10 of int"
typedef int IntArray10[10];

// Equivalent to the preceding definitions
IntArray10 *foo(float arg1, char arg2) { ... }
IntArray10 &bar(float arg1, char arg2) { ... }