写一个用回调代替switch case代码
时间: 2023-04-06 10:00:52 浏览: 55
好的,我可以回答这个问题。使用回调函数可以将代码更加模块化,使得代码更加易于维护和扩展。下面是一个示例代码:
```c
#include <stdio.h>
typedef void (*callback)(int);
void case1(int value) {
printf("Case 1: %d\n", value);
}
void case2(int value) {
printf("Case 2: %d\n", value);
}
void case3(int value) {
printf("Case 3: %d\n", value);
}
void switch_case(int value, callback cb) {
cb(value);
}
int main() {
int value = 2;
switch_case(value, case1);
switch_case(value, case2);
switch_case(value, case3);
return 0;
}
```
在上面的代码中,我们定义了三个回调函数 case1、case2 和 case3,它们分别对应 switch case 中的三个分支。然后我们定义了一个 switch_case 函数,它接受一个整数和一个回调函数作为参数。在 switch_case 函数中,我们调用了传入的回调函数,并将整数作为参数传递给它。最后在 main 函数中,我们调用了 switch_case 函数三次,每次传入不同的回调函数,从而模拟了 switch case 的效果。