当前位置:网站首页>Advanced usage of C language -- function pointer: callback function; Conversion table
Advanced usage of C language -- function pointer: callback function; Conversion table
2022-07-02 14:22:00 【Look, mountains are mountains_ Lau】
The two most common uses of function pointers : Pass as argument to another function ( Callback function ) And conversion table (jump table), This article will explore some skills in these two aspects .
One . Callback function
There is a simple function , It is used to find a value in a single linked list . Its parameter is a point to the list number 1 The pointer of the node and the value to be found .
Node*
search_list (Node *node, int const value)
{
while (node != NULL)
{
if (node->value == value)
break;
node = node->link;
}
return node;
}
This function looks quite simple , But it only applies to linked lists with integer values . If you need to find in a string linked list , You have to write another function . Most of the code of this function is the same as that of the above function , Only the type of the second parameter and the comparison method of node values are different .
A more general approach is to make the lookup function type independent , In this way, it can be used for linked lists of values of any type . We have to modify two aspects of the function , Make it type independent .
First , We must change the way comparisons are performed , In this way, the function can compare any type of value . This goal sounds impossible , If you write statements to compare integer values , How can it also be used for comparison of other types such as strings ? The solution is to use A function pointer . The caller writes a function , Used to compare two values , Then pass a pointer to this function as a parameter to the lookup function . Then the lookup function calls this function to perform a value comparison . Using this method , Any type of value can be compared .
secondly , Pass a pointer to the value to the function instead of the value itself . The function has one void *
Shape parameter , Used to receive this parameter . Then a pointer to this value is passed to the comparison function . String and array objects can also be used in this modification . Strings and arrays cannot be passed as parameters to arrays , But the pointer to them can .
The function that uses this technique is called Callback function (callback function), Because the user passes a function pointer as a parameter to other functions , The latter will “ Callback ” The user's function . anytime , If the function you write must be able to perform different types of work at different times, or perform work that can only be defined by the function caller , You can use this technique .
We cannot write an accurate prototype for the callback function in this context , Because we don't know the type of value to compare . in fact , We need to find functions that can act on any type of value . The way to solve this problem is to declare the parameter type as void *
, Express “ A pointer to an unknown type ”
The following code is an implementation method of type independent lookup function . Notice that the third parameter of the function is a function pointer .
/* ** Find a function with a specified value in a single linked list . Its parameter is a pointer to the first node of the linked list ** A pointer to the value we need to find and a function pointer , The function it points to is used to compare the values of types stored in the linked list */
#include <stdio.h>
#include "node.h"
Node *
search_list (Node *node, void const *value,
int (*compare)(void const *, void const*))
{
while (node != NULL)
{
if (compare(&node->value, value) == 0)
break;
node = node->link;
}
return node;
}
int
compare_ints (void const *a, void const *b)
{
if (*(int *)a == *(int *)b)
return 0;
else
return 1;
}
This function will be used as follows :
desired_node = search_list(root, &desired_value, compare_ints);
Two . Transfer table
The transfer table is best explained by an example . The following code snippet is taken from a program , It is used to realize a pocket calculator . The rest of the program has read in two numbers (op1
and op2
) And an operator (oper
). The following code tests the operator , Then decide which function to call .
switch (oper)
{
case ADD:
result = add(op1, op2);
break;
case SUB:
result = sub(op1, op2);
break;
case MUL:
result = mul(op1, op2);
break;
case DIV:
result = div(op1, op2);
break;
...
}
For a novel calculator with hundreds of operators , This article switch
The statement will be very long .
Why call functions to perform these operations ? It is a good design scheme to separate the code of specific operation and selection operation . More complex operations will be implemented by independent functions , Because they can be very long . But even simple operations can have side effects , For example, save a constant value for future operations .
In order to make switch
sentence , The code representing the operator must be an integer . If they are consecutive integers starting from zero , We can use the transformation table to achieve the same task . The conversion table is an array of function pointers .
Creating a transformation table requires two steps . First , Declare and initialize an array of function pointers . The only thing to pay attention to is to ensure that the prototypes of these functions appear before the declaration of this array .
double add (double, double);
double sub (double, double);
double mul (double, double);
double div (double, double);
...
double (*oper_func[]) (double, double) =
{
add, sub, mul, div,...};
The correct order of function names in the initialization list depends on the integer code used by the program to represent each operator . This example assumes that ADD yes 0,SUB yes 1,MUL yes 2, And so on .
The second step is to replace the whole previous sentence with the following sentence switch
sentence !
result = oper_func[oper] (op1, op2);
oper
Select the correct function pointer from the array , The function call operator will execute this function .
Thank you for reading :)
inner peace
Unity of
---------------------END---------------------
边栏推荐
- In 2021, the global revenue of structural bolts was about $796.4 million, and it is expected to reach $1097.6 million in 2028
- The most complete analysis of Flink frame window function
- 路由(二)
- 【虹科技术分享】如何测试 DNS 服务器:DNS 性能和响应时间测试
- Essential elements of science fiction 3D scenes - City
- 每天坚持20分钟go的基础二
- QT new project_ MyNotepad++
- Multi rotor aircraft control using PID and LQR controllers
- Available solution development oral arithmetic training machine / math treasure / children's oral arithmetic treasure / intelligent math treasure LCD LCD driver ic-vk1622 (lqfp64 package), original te
- STM32-DAC实验&高频DAC输出测试
猜你喜欢
每日学习2
Packet capturing tool Fiddler learning
Development and design of animation surrounding mall sales website based on php+mysql
QT new project
Will your sleep service dream of the extra bookinfo on the service network
Code implementation MNLM
关于Flink框架窗口(window)函数最全解析
YOLOv3&YOLOv5输出结果说明
Qt新建项目
Daily learning 3
随机推荐
提示:SQL Server 阻止了对组件‘Ad Hoc Distributed Queries ‘的STATEMENT ‘OpenRowset/OpenDatasource“”
Penetrate the remote connection database through the Intranet
C crystal report printing
HMS core machine learning service helps zaful users to shop conveniently
Packet capturing tool Fiddler learning
Convolutional neural network (Introduction)
Codeforces Round #803 (Div. 2)(A~D)
YOLOv3&YOLOv5输出结果说明
Golang quickly generates model and queryset of database tables
STM32-DAC实验&高频DAC输出测试
QT - make a simple calculator - realize four operations
uni-app中使用computed解决了tab切换中data()值显示的异常
Yolov3 & yolov5 output result description
Go operation redis
php链表创建和遍历
【虹科技术分享】如何测试 DNS 服务器:DNS 性能和响应时间测试
MySQL 45 lecture - learning the actual battle of MySQL in Geek time 45 Lecture Notes - 05 | easy to understand index (Part 2)
In 2021, the global revenue of structural bolts was about $796.4 million, and it is expected to reach $1097.6 million in 2028
Teamtalk source code analysis win client
Chinese science and technology from the Winter Olympics (III): the awakening and evolution of digital people