gpt4 book ai didi

c - 使用回调的优点(在非事件驱动程序中)

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:20 25 4
gpt4 key购买 nike

我正在研究一个回调示例: https://en.wikipedia.org/wiki/Callback_(computer_programming)

#include <stdio.h>
#include <stdlib.h>

/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
int val1 = numberSource();
int val2 = numberSource();
printf("%d and %d\n", val1, val2);
}

/* A possible callback */
int overNineThousand(void) {
return (rand()%1000) + 9001;
}

/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}

/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}

我了解所有功能。但是,我想知道除了减少一行之外,这样做的好处是什么:

PrintTwoNumbers(&overNineThousand);

而不是像常规函数一样使用它们:

int a = overNineThousand();
PrintTwoNumbers(a);

谢谢!

最佳答案

这是所谓的 Higher Order Function 的一个简单示例.

在这个特定的例子中,它不是很有用。你是对的,直接传递数据会更容易。

不过,这是一种允许函数泛化的技术,如果使用得当,对于减少代码重复非常有帮助。

一个典型的例子是转换列表的 map 函数:

var arr = [1, 2, 3];
var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

print(newArr); // Prints [2, 3, 4]

如果没有高阶函数,每次要转换列表时,您都必须编写包含 map 的相同循环代码。如果我想给其他地方的每个元素加 2 怎么办?还是每个乘以 5?通过传递一个函数,您可以告诉它您希望它如何转换每个项目,而无需担心迭代。

如评论中所述,另一个示例是排序函数。它们允许您传递确定排序顺序的函数。如果没有这种能力,您将需要为每个不同的排序顺序和元素类型编写一个新的排序函数。


抱歉,我无法用 C 语言回答这个问题。我明白您发布的代码中发生了什么,但我不懂 C,所以我无法提供使用 HOF 的良好示例代码。

关于c - 使用回调的优点(在非事件驱动程序中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438949/

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