C/C++ Arena

Step 1 of 6

Functions have addresses

A function lives in memory like everything else, so you can store its address in a function pointer and call it later:

int add(int a, int b) { return a + b; }

int (*op)(int, int) = add;   // op points at add
printf("%d\n", op(2, 3));    // 5

Read int (*op)(int, int) as: "op is a pointer to a function taking (int, int) and returning int". The parentheses around *op matter: without them, int *op(int, int) declares a function returning int *.

Your turn: point op at sub and call it.

Next: typedef and passing callbacks