A pointer can hold a function. Pass one to another function to choose behaviour at run time.
C · beginner · 7 min · 13 steps · free
#include <stdio.h>
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int apply(int (*op)(int, int), int x, int y) {
return op(x, y);
}
int main(void) {
int (*choice)(int, int) = add;
int r1 = apply(choice, 3, 4);
choice = mul;
int r2 = apply(choice, 3, 4);
printf("%d %d\n", r1, r2);
return 0;
}apply(), with op = → add(), x = 3 and y = 4. It gets its own variables on the stack.add() has finished, so its variables are gone.apply() has finished, so its variables are gone. The value it returned, 7, is stored in r1.apply(), with op = → mul(), x = 3 and y = 4. It gets its own variables on the stack.mul(), with a = 3 and b = 4. It gets its own variables on the stack.mul() has finished, so its variables are gone.apply() has finished, so its variables are gone. The value it returned, 12, is stored in r2.7 12.0.Answer: int (*f)(int). Without parentheses it is a function returning int*.
Answer: A function pointer. You pass the compare function.
← Pointers to Pointers · Structs →