2019-08-17 | 编程语言 | UNLOCK

跳转表(Jump table)

最近在看《C和指针》,觉得这个东西还挺有意思的,记录一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>

enum Opt {
ADD=0, SUB, MUL, DIV
}opt;

double add(double a, double b) {
return a+b;
}
double sub(double a, double b) {
return a-b;
}
double mul(double a, double b) {
return a*b;
}
double div(double a, double b) {
return a/b;
}
double (*f[])(double, double)={add, sub, mul, div};
int main(void) {
opt = SUB;
printf("%lf\n", f[opt](4.3, 2.7));
return 0;
}