The pointer to the function.
(1) function pointer
Definition: If a function is defined in a program, the compilation system allocates a bucket for the function code during compilation. The starting address of this bucket is the pointer of this function.
(2) using function pointer variables to call Functions
Small example, taking the maximum value
# Include <stdio. h> int main () {int max (int x, int y); int (* p) (int, int ); // define the pointer Variable p int a = 0, B = 0, c = 0; p = max; scanf ("% d", &, & B); printf ("% d \ n", a, B); c = (* p) (a, B ); // call the max function printf ("% d", c) using pointer variables;} int max (int x, int y) {int z; if (x> y) z = x; else z = y; return (z );}
It can be seen that the general format of the pointer variable pointing to the function is defined.
Type name (* pointer variable name) (function parameter list)
Int (* p) (int, int) p is a pointer variable pointing to a function. It can only point to the function entry, not to a certain instruction in the middle of the function.
(3) pointing to a function pointer as a parameter
In this example, the user inputs two numbers a and B. When the user inputs 1, the maximum value of the two numbers is obtained. When the user inputs 2, the minimum value of the two numbers is obtained. When the user inputs 3, returns the sum of two numbers.
Define a fun function. Each time you make different function names as real parameters, you can send the entry address to the form parameters in the fun function (that is, the pointer variable pointing to the function)
1 # include <stdio. h> 2 int main () {3 int fun (int x, int y, int (* p) (int, int )); // fun function declaration 4 int max (int, int); 5 int min (int, int); 6 int add (int, int); 7 int a, B, n; 8 scanf ("% d", & a, & B); 9 printf ("select 1, 2, 3 \ n"); 10 scanf ("% d ", & n); 11 if (n = 1) fun (a, B, max); // call the max function 12 else if (n = 2) when entering 1) fun (a, B, min); // input 2 min function 13 else if (n = 3) fun (a, B, add ); // input 3 call the add function 14 return 0; 15} 16 int fun (int x, int y, int (* p) (int, int) {17 int result; 18 result = (* p) (x, y); 19 printf ("% d \ n", result); 20} 21 int max (int x, int y) {// take the maximum value 22 int z; 23 if (x> y) z = x; 24 else z = y; 25 return (z ); 26} 27 int min (int x, int y) {// take the minimum value 28 int z; 29 if (x <y) z = x; 30 else z = y; 31 return (z); 32} 33 int add (int x, int y) {// calculate the sum of the two numbers 34 int z; 35 z = x + y; 36 return (z); 37}