I read a piece of code and find there is a function like that.
int (*function())[10]{
...
}
I am confused. What does this function mean and what will it return?
It is the definition of a function that returns a pointer to an array of 10 integers.
Remember that the return value is a pointer, not an actual array. Arrays cannot be returned from functions. Per paragraph 8.3.5/8 of the Standard:
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
Here's a simple example of how you would use it:
int arr[10]; // an array of 10 int
int (*ptr)[10]; // pointer to an array of 10 int
int (*function())[10] // function returning a pointer to an array of 10 int
{
return ptr;
}
int main()
{
int (*p)[10] = function(); // assign to the pointer
}
You can use this wherever you would normally use a pointer. But note that there are better alternatives than pointers altogether, like std::shared_ptr<std::array<T, N>>
or std::shared_ptr<std::vector<T>>
.
The way to read it is to find the leftmost identifier and work your way out, remembering that ()
and []
bind before *
, so *a[]
is an array of pointers, (*a)[]
is a pointer to an array, *f()
is a function returning a pointer, and (*f)()
is a pointer to a function. Thus,
function - function
function() - is a function
*function() - returning a pointer
(*function())[10] - to a 10-element array
int (*function())[10] - of int
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