5

Why does this code require the '&' in array syntax?

int (&returnArray(int (&arr)[42]))[42]
{
  return arr;
}

When i declare it like this

int (returnArray(int arr[42]))[42]
{
  return arr;
}

i get

error C2090: function returns array

But isn't this an array it was returning in the first example? Was it some sort of a reference to array?

I know i can also pass an array to a function, where it will decay to a pointer

int returnInt(int arr[42])
{
  return arr[0];
}

or pass it by reference

int returnInt(int (&arr)[42])
{
  return arr[0];
}

But why can't i return an array the same way it can be passed?

spiritwolfform
  • 2,263
  • 15
  • 16

2 Answers2

6
int (&returnArray(int (&arr)[42]))[42]

The first & means this would return a reference to the array.

This is required by the standard :

8.3.5 Functions §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. »

Community
  • 1
  • 1
zakinster
  • 10,508
  • 1
  • 41
  • 52
  • does it make sense because passing arrays as parameters **decays** into pointer ? thus implying the original type was always "array" and not pointer and as such cannot be expected to be returnable as a pointer type ? so this reflects the weirdness into why do we have decay at all. – v.oddou Apr 23 '15 at 05:16
3

The first function is not returning an array, it's returning a reference to an array. Arrays cannot be returned by value in C++.

These topics are generally well covered in good C++ books.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455