Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ array syntax (function returns array)

Tags:

c++

arrays

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?

like image 859
spiritwolfform Avatar asked May 07 '13 07:05

spiritwolfform


People also ask

Can function return type array?

We can also make a function return an array by declaring it inside a structure in C++. Let us see how. Here, note that we have declared the array arr inside the structure demo . And this time the function has a return type of the structure itself and return demo_mem (structure variable) instead of the array.

How can a function return a local array?

A local array cannot be directly returned from a C++ function as it may not exist in memory after the function call. A way to resolve this is to use a static array in the function. As the lifetime of the static array is the whole program, it can easily be returned from a C++ function without the above problem.

What is * array [] in C?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].


1 Answers

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

like image 68
zakinster Avatar answered Oct 01 '22 03:10

zakinster