1. 函数也有地址
C 语言里,函数和变量一样,都有自己的地址。
既然有地址,就能被指针指向。
2. 函数指针的声明方式
格式:
返回值类型 (*指针名)(参数列表)
例:
int (*fp)(int, int);
表示:
-
fp 是一个指针
-
它指向一个参数为 (int, int) 的函数
-
返回值 int
3. 函数指针的初始化
fp = add;
C 中函数名本质上就是函数地址。
4. 使用函数指针调用函数
int r = fp(1,2);
它和直接 add(1,2) 完全等价。
5. typedef 简化写法
typedef int (*callback)(int); callback cb = func;
优点:
-
可读性强
-
使用方便
6. 函数指针数组
你可以把多个函数指针装入数组:
callback table[3] = {func1, func2, func3};
然后通过索引调用:
table[1]();
示例:
#include <stdio.h>
typedef enum {
A_TO_B,
B_TO_A,
A_TO_C,
C_TO_A,
C_TO_B,
B_TO_C,
STATUS_MAX,
} Status;
struct Car {
Status current_status;
};
typedef int (*callback)(struct Car*);
int a2b(struct Car*car) {
// a到b所需要做的行为
printf("a到b\n");
return 1;
}
int b2a(struct Car *car) {
// b到a所需要做的行为
printf("b到a\n");
return 1;
}
int a2c(struct Car *car) {
// a到c所需做的行为
printf("a到c\n");
return 1;
}
int c2a(struct Car *car) {
// c到a所需要做的行为
printf("c到a\n");
return 1;
}
int c2b(struct Car *car) {
// c到b所需要做的行为
printf("c到b\n");
return 1;
}
int b2c(struct Car *car) {
// b到c所需要做的行为
printf("b到c\n");
return 1;
}
int main() {
callback callbacks[STATUS_MAX] = {a2b, b2a, a2c, c2a, a2b, b2c};
Status status[4] = {A_TO_B, B_TO_A, A_TO_C, C_TO_A};
int i = 0;
struct Car car;
car.current_status = status[i];
while (i < 4) {
// 状态结束
if (callbacks[car.current_status](&car)) {
i++;
car.current_status = i;
//i %= 4; // 处理状态的个数
}
}
}