c 语言的回调函数举例
时间: 2023-07-12 21:27:35 浏览: 49
回调函数是指把一个函数作为参数传递给另一个函数,在另一个函数内部调用这个函数。在 C 语言中,回调函数通常被用于异步编程、事件处理等场景。下面是一个回调函数的简单示例:
```c
#include <stdio.h>
// 回调函数的定义
void callback(int num) {
printf("This is a callback function, the number is %d\n", num);
}
// 接受回调函数作为参数的函数
void do_something(int num, void (*callback_func)(int)) {
printf("do something...\n");
// 调用回调函数
callback_func(num);
}
int main() {
// 调用 do_something 函数,传递回调函数作为参数
do_something(123, callback);
return 0;
}
```
在上面的示例中,`do_something` 函数接受一个整型参数 `num` 和一个回调函数 `callback_func`,在函数内部调用回调函数,并把 `num` 作为参数传递给回调函数。在 `main` 函数中,调用 `do_something` 函数并传递回调函数 `callback` 作为参数。程序输出:
```
do something...
This is a callback function, the number is 123
```