What is "int *(*pfp) ();" doing in C?
What does th开发者_如何学Gois do?
int *(*pfp) ();
int *(*pfp) ();
Creates a pointer to a function that returns int*. The function pointer name ispfp
.
Here's an example:
int* myFunc(void)
{
return NULL;
}
int main(int argc, char**argv)
{
int *(*pfp) (void);
pfp = myFunc;
return 0;
}
Note: Since the parameters of the function pointer is not (void) that you gave, that means that the parameter list is not specified in C. In C++ it would mean that it's a function with no parameters exactly.
Brian's explained the "what", but if you're curious as to the why, here's an excerpt from Dennis Ritchie's The Development of the C Language:
The second innovation that most clearly distinguishes C from its predecessors is this fuller type structure and especially its expression in the syntax of declarations. NB offered the basic types int and char, together with arrays of them, and pointers to them, but no further ways of composition. Generalization was required: given an object of any type, it should be possible to describe a new object that gathers several into an array, yields it from a function, or is a pointer to it.
For each object of such a composed type, there was already a way to mention the underlying object: index the array, call the function, use the indirection operator on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,
int i, *pi, **ppi;
declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that i, *pi, and **ppi all yield an int type when used in an expression. Similarly,
int f(), *f(), (*f)();
declare a function returning an integer, a function returning a pointer to an integer, a pointer to a function returning an integer;
int *api[10], (*pai)[10];
declare an array of pointers to integers, and a pointer to an array of integers. In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration.
For more info, read Steve Friedl's "Reading C type declarations" or Eric Giguere's "Reading C Declarations: A Guide for the Mystified".
pfp
is a pointer to a function that takes no parameters (or indeterminate parameters in C) and returns a pointer to an int
.
Using the 'clockwise-spiral' rule is an effective way to decipher complex C declarations (at least I find it effective):
- http://c-faq.com/decl/spiral.anderson.html
Use http://www.cdecl.org/ for these things, if you're not sure.
精彩评论