1. Function PointersThe ① function also has an address in memory. Function names represent memory addresses of functionsThe ② function pointer is a pointer to a function variablethe ③ function is stored in the code area④ function pointer definitions are similar to function declarations⑤function Declaration: int maxValue (int x, int y);function pointer definition: INT (*p) (int x, int y);Anatomy of a ⑥ function pointerInt (*p) (int x, int y) variable definition three parts:type: Int (*) (int x, int y)variable name: PInitial value: NULLThe address of the ⑦ function is fixed, but the address of the pointer variable can be changed back and forth⑧ function pointer definition"1" typically uses TypeDef to define function pointer types"2" typedef int (*pfun) (int x, int y);//parameter can be omitted"3" Pfun is a new type name after typedef"4" pfun p = NULL;"5" type variable initial value⑨ function pointer Assignment value"1" p = maxvalue;//after p can be used as MaxValue"2" function name represents the entry address"3" functions that assign values to function pointers should be consistent with function prototypes defined by function pointers⑩ Example:typedef int (*pfun) (int, int);//equivalent to changing int (*) (int, int) to Pfunint sum (int a, int b);int sum (int a, int b) {//addition functionreturn a+b;
}int MaxValue (int x, int y);int MaxValue (int x, int y) {//MAX functionreturn x>y?x:y;
}int main () {pfun P1 = sum;//defines a pointer variable p1, and the past sum address Int (*p) (int a, int b);p = sum;//pointer variable p gets the sum address int x = P (30,20);printf ("%d\n", x); p = maxvalue;//the same type pointer variable can get multiple function addressesprintf ("%d", p (100,30));
}2. Function Callback① callback Function (callback): A callback function is a function that is implemented by the caller itself and is used by the calling partyThe ② function callback is a very flexible design pattern, which is widely used in practice. ③ callback function core function pointer as parameterExample:int revalue (int a, int b, int (*p) (int, int));use:int m = GetValue (3,5,maxvalue);//m is 5.④ Example:typedef int (*pfun) (int, int);//equivalent to changing int (*) (int, int) to Pfunint sum (int a, int b);int sum (int a, int b) {//addition functionreturn a+b;
}int MaxValue (int x, int y);int MaxValue (int x, int y) {//MAX functionreturn x>y?x:y;
}int minus (int x, int y);int minus (int x, int y) {//subtraction functionreturn x-y;
}int GetValue (int x, int y, pfun p);int GetValue (int x, int y, Pfun p) {//callback functionreturn p (x, y);
}int main () {int a = GetValue (ten, MaxValue);//MAX valueint B = GetValue (+, +, sum);//Summationint c = getValue (5, minus);//Seek reductionprintf ("%d%d%d\n", a,b,c);
}
16. Primary function pointer (function pointer and function call)