1. Function pointers: pointer variables pointing to functions.
Functions also have addresses in memory, and function names represent the memory addresses of functions.
Example: function: int sum (int a,int b);
int sum (int a,int b) {
return a+b;
}
Function name + formal parameter is a function
Function pointer: function pointer definition: INT (*p) (int a,int b);
technique, the assignment function declares an int sum (int a,int b), encloses sum with an * number, changes sum to a name, defines a function pointer, p is the variable, p = sum;int x = SUM (2,3); int x = P (2,3) ; equivalence
2. Function pointer anatomy
Int (p*) (int a,int b) = NULL;
Type: int (*) (int a,int b)
Variable name: P
Initial value: NULL
3. p = sum;
p = naxvalue;
P can point to any function;
4. typedef int (*pfun) (int,int);
The equivalent of changing int (*) (int a,int b) to Pfun;
Pfun p = NULL;
P = sum;
Assigning a value to a function pointer must be consistent with the defined type. At this point the type of P is int
5. Callback function
Callback
The function callback core is the function as the formal parameter;
Example: int maxValue (int x,int y) {
Return a > B? A:B;
}
int getValue (int x, int y) {
return sum (x, y);//at which time GetValue is summed; when called int a = GetValue (2,4);
or return MaxValue (x, y); //At this time GetValue is the maximum value; when called int a = GetValue (2,4);
The use of which will have to change the internal implementation of the GetValue function, not flexible, more trouble!!!!
}
int GetValue (int x, int y,pfun p) {(Pfun p represents a function pointer that the return value is an integer)
return p (x, y);
}
int a = GetValue (2,4,maxvalue);
int b = GetValue (2,4,sum);
two kinds of implementations, GetValue not change a bit, just pass the value of the parameter. You can also add other functions, p feel free to refer to, very convenient.
such as Thunderbolt company, at this time GetValue is the core of the code, is intellectual property, will not let the programmer modify, upgrade only add functions, and then the main function call can be
C Language---Function pointers (beginner)