问题
At least by the C11 standard and from what I've read.
The only place where return type is not allowed to be an array type is in the section of function definitions (at $6.9.1.3):
The return type of a function shall be void or a complete object type other than array type.
At function calls ($6.5.2.2.1) it states this:
The expression that denotes the called function shall have type pointer to function returning void or returning a complete object type other than an array type.
Which means that something like this would be expected:
int (*pf1)()[4]; //legal?
pf1(); //error calling a function which return array
What I mean is that from how I understand the standard only defining a function returning arrays is illegal and not defining a pointer to function returning arrays. Prove me wrong if you can. Also if I'm wrong I would be happy if you explain me why is this sentence in the standard then?
Although clang doesn't seems to think that way and will rise an error in the above code stating that 'function cannot return array type 'int [4]''. But is this really a function (and not rather a pointer to one)?
EDIT:
OK - I was answered by citation of the standard paper that 'function declarators' can't have a return-type of array. However if we use a typedef name instead to declare a pointer to function returning arrays - would this be legal? -
typedef int arr_t[4];
arr_t (*pf1)(void);
Although I personally think that this case is also covered by the answers because the type-name defined by a 'typedef' is the same as one explicitly defined.
回答1:
The sentence that you found is indeed only about function definitions, not about declarations. However, you missed another constraint:
6.7.5.3 Function declarators (including prototypes)
Constraints
1 A function declarator shall not specify a return type that is a function type or an array type.
Also if I'm wrong I would be happy if you explain me why is this sentence in the standard then?
There needs to be an additional requirement that a called function returns a complete object type because a function declaration is allowed to declare it as returning an incomplete type:
struct S;
struct S f(); /* valid */
void g() { f(); } /* invalid */
struct S { int i; };
void h() { f(); } /* valid */
It's not about arrays. The wording about "other than an array type" is just to make sure arrays don't accidentally become allowed by a mistake in the wording.
回答2:
Declaring pointers to function returning arrays is actually legal?
No. Its not legal. You will get a compile time error. A function can't return an array.
For the time being, if int (*pf1)()[4];
is valid anyhow, then the function call
pf1();
doesn't make any sense. pf1
is not pointing to any function.
来源:https://stackoverflow.com/questions/34579977/declaring-pointers-to-function-returning-arrays-is-actually-legal