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?

3
  • @john I'd guess all C++ books worth their salt should mention array value semantics. Commented May 7, 2013 at 7:42
  • possible duplicate of Why doesn't C++ support functions returning arrays? Commented May 7, 2013 at 7:46
  • i tried to edit the question to show that it's a little bit different from that one Commented May 7, 2013 at 8:03

2 Answers 2

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. »

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.