gpt4 book ai didi

C 中的回调函数与普通函数

转载 作者:太空狗 更新时间:2023-10-29 15:28:54 25 4
gpt4 key购买 nike

我正在学习 C 中的回调函数,但发现自己太难理解了回调的概念。

据我所知,回调函数是使用 c 中的函数指针实现的,这意味着我们可以通过使用指针来引用函数,就像我们使用指针一样引用一个变量。

我这里有两个函数的实现:

1.首先是使​​用回调函数

#include <stdio.h>

int add_two_number(int a, int b);
int call_func(int (*ptr_func)(int, int), int a, int b);

int main (int *argc, char *argv[])
{
printf("%d", call_func(add_two_number, 5, 9));

return 0;
}

int add_two_number(int a, int b)
{
return a + b;
}

int call_func(int (*ptr_func)(int, int), int a, int b)
{
return ptr_func(a, b);
}

2.第二种是使用普通的函数调用:

#include <stdio.h>

int add_two_number(int a, int b);
int call_two_number(int a, int b);

int main (int *argc, char *argv[])
{
printf("%d", call_two_number(5, 9));

return 0;
}

int add_two_number(int a, int b)
{
return a + b;
}

int call_two_number(int a, int b)
{
return add_two_number(a, b);
}

这两个函数在两个数字和这两个数字之间做简单的数学加法功能也如我所料正常工作。

我的问题是这两者有什么区别?以及何时使用回调而不是普通函数?

最佳答案

当你不知道你想在调用的地方调用什么函数时使用回调。例如,如果您还想减去两个数字怎么办:

#include <stdio.h>

int add_two_number(int a, int b);
int sub_two_number(int a, int b);
int call_func(int (*ptr_func)(int, int), int a, int b);

int main (int *argc, char *argv[])
{
// Here is where we decide what the function should do for the first call
printf("%d", call_func(add_two_number, 5, 9));
// Here is where we decide what the function should do for the second call
printf("%d", call_func(sub_two_number, 5, 9));
return 0;
}

int add_two_number(int a, int b)
{
return a + b;
}

int sub_two_number(int a, int b)
{
return a - b;
}

int call_func(int (*ptr_func)(int, int), int a, int b)
{
return ptr_func(a, b); // Here is the place the call is made
}

回调对于解耦代码也很有用。考虑一个带有多个按钮的应用程序。如果没有回调,您将不得不在按钮代码中使用一些逻辑来确定单击每个按钮时会发生什么。通过使用回调,按钮代码可以保持通用,但每个按钮仍然可以在单击时调用不同的操作。

关于C 中的回调函数与普通函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com