简体   繁体   中英

c++ array syntax (function returns array)

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM