Function pointers in C
A function's name is an address, so it can be stored, passed and called.
static int add(int a, int b) {
return a + b;
}
static int multiply(int a, int b) {
return a * b;
}
int apply(int (*op)(int, int), int a, int b) {
return op(a, b);
}
int dispatch(int which, int a, int b) {
int (*table[2])(int, int) = {add, multiply};
if (which < 0 || which > 1) {
return 0;
}
return table[which](a, b);
}
How it works
int (*op)(int, int)is a pointer to such a function.- The name alone is enough; the ampersand is optional.
- A table of them replaces a long switch.
Keywords and builtins used here
addapplydispatchifintmultiplyreturnstatic
The run, in numbers
- Lines
- 19
- Characters to type
- 323
- Tokens
- 125
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 79 seconds.
Step 2 of 4 in Generic & function pointers, step 7 of 25 in Pointers & memory.