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?
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.
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.
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 [].
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. »
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With