Function pointer
A function pointer is a pointer variable that points to a function.
Usually, the pointer variable we refer to points to a variable such as an integer, character, or array, whereas a function pointer points to a function.
A function pointer can be used like a normal function to call functions and pass parameters.
Declaration of function pointer type:
typedef int (*fun_ptr)(int,int); // 声明一个指向同样参数、返回值的函数指针类型
Example
The following example declares a function pointer variable p, pointing to the function max:
Example
Compile and execute, the output result is as follows:
请输入三个数字:1 2 3 最大的数字是: 3
callback function
Function pointer as a parameter of a function
A function pointer variable can be used as a parameter of some function; a callback function is a function called through a function pointer.
Simply put: a callback function is a function you implement that is called during the execution of someone else's function.
The following is an explanation from the Zhihu author Chang Xiling:
You go to a store to buy something, but the item you want happens to be out of stock, so you leave your phone number with the clerk. A few days later, the item is in stock, and the clerk calls you; upon receiving the call, you go to the store to pick up the item. In this example, your phone number is called the callback function, leaving your phone number with the clerk is called registering the callback function, the later arrival of the item in stock is called triggering the callback-related event, the clerk calling you is called invoking the callback function, and your going to the store to pick up the item is called responding to the callback event.
Example
in the examplepopulate_array()The function defines three parameters, the third of which is a function pointer; the array values are set through that function.
In the example, we defined a callback functiongetNextRandomValue()It returns a random value, and it is passed as a function pointer topopulate_array()function.
populate_array()will call10the callback function, and assigns the return value of the callback function to the array.
Example
Compile and execute, the output result is as follows:
16807 282475249 1622650073 984943658 1144108930 470211272 101027544 1457850878 1458777923 2007237709other extensions