Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange function syntax: auto (*f3)(int n)->int (*)[n];

Tags:

c++

I came across this weird function syntax:

const int n = 3;

auto (*f3)(int n)->int (*)[n]; //error: parameter 'n' as array bound

while reading about scope at this page at cppreference.com.

Although the second statement is an error, how do you interpret it? (assuming the scope error was rectified)

I think the first part is a pointer to function but its the part from the -> onwards thats got me stumped.

Can someone point me in the right direction? Thanks

like image 528
neophyte Avatar asked Feb 09 '23 21:02

neophyte


2 Answers

Although the second statement is an error, how do you interpret it? (assuming the scope error was rectified)

Example shows you the difference btw 2 cases:

const int n = 3;

int (*(*f2)(int n))[n];

is basically equivalent to:

const int n = 3;

int (*(*f2)(int n1))[n];

while

const int n = 3;

auto (*f3)(int n)->int (*)[n];

is equivalent to:

const int n = 3;

auto (*f3)(int n1)->int (*)[n1];

and article exlains why. If you mean fixing this code by:

const int n = 3;

auto (*f3)(int n1)->int (*)[n];

then it would declare a pointer to function that accept one parameter of type int and returns pointer to array of 3 ints.

like image 194
Slava Avatar answered Feb 16 '23 04:02

Slava


The -> syntax with auto and trailing return type is new in C++11. You can't directly apply the inside-out declaration interpretation rules to the whole thing, only to the separate parts to the left of -> and to the right of ->.

If we get rid of the error

const int n = 3;
auto (*f3)(int m) -> int (*)[n];

then the proper equivalent "classic" version can be written as

const int n = 3;
typedef int (*T)[n];

T (*f3)(int m);

i.e. the int (*)[n] part is the return type.

In other words

T (*f3)(int m);

and

auto (*f3)(int m) -> T;

are the same thing. The typedef helps to emphasize the equivalence.

like image 42
AnT Avatar answered Feb 16 '23 03:02

AnT