function pointer with its beautiful appearance puzzled the students for a long time, this article strives to let students thoroughly understand the use of function pointers.
First of all, there are two points must be understood, do not understand also have to remember first.
- The shape of a function pointer
- Rules for defining the C + + identifier type
Declare the shape of the function pointer as follows
char (*F_PTR) (int, double);//return type (* identifier) (parameter list)
In other words, unlike other common type declaration methods, the function pointerStatementis not a form of [type identifier] (such as int a). SuchStatementF_ptr is a function pointer pointing to the address of a function.
What are the declaration rules for C/C + + identifiers, and what is popular about:For a statement that declares an identifier, remove the semicolon and the identifier itself, leaving the type of the identifier. In this sentence, the declaration statement of the polygon function pointer is processed, and the
CHAR (*) (int,double)
This is the type of F_ptr recall F_ptr method of invocation
- To obtain the corresponding function of the address.
- Parameter invocation
Because the parentheses () have a higher precedence than *, the solution must be bracketed
char res = (*f_ptr) (1, 2.5);
Here are three examples to further illustrate the use of function pointers
void func1 (int k) {printf ("%d in Func 1\n", k);} int main () {/** Direct method: Declares and initializes a function pointer and then calls */void (*FP) (int) = &func1; (*FP) (2);/** defines type identity fp_type as void (*) using a Type definition simplified declaration (int ), then define the function pointer */typedef void (*fp_type) (int); Fp_type FP2 = &func1; (*FP2) (3);/** type conversion: Converting a void * Pointer to a function pointer type using (conversion type) conversion Object Format */void* FP3 = &func1; (* (void (*) (int)) FP3) (4); system ("pause");
What, do you think you're going to use a function pointer? Understanding the relationship between the type and the identifier, the next written test lets you write a function pointer array with a parameter as a function pointer without fear.
void (*b[10]) (void (*) ());
There are many interesting examples of function pointers, as seen in this blog post. Q: What is the meaning of signal
void (*signal (int,void (*) (int))) (int);
Here, signal is not a function pointer, is a function, its return value is a function pointer, how to analyze it? First look at the outermost void (* BlaBla) (int), which means that BlaBla is a function pointer and BlaBla is a signal (int, pointer), it is obvious that "identifier (type)" is the function signature, and the meaning is the return value of the function.
Please correct me!
Simple analysis of C + + function pointers