C/C++ Arena

Step 2 of 6

typedef and passing callbacks

Function pointer types get unreadable fast, so give them a name with typedef:

typedef int (*BinOp)(int, int);

Now BinOp is a type, and you can pass behavior into a function. The function you pass is called a callback:

int fold(const int *a, int n, int init, BinOp f);
fold(a, n, 0, add);   // sum
fold(a, n, 1, mul);   // product

Your turn: write fold. It starts with init and combines it with each element in order: acc = f(acc, a[i]).

Previous: Functions have addresses Next: A dispatch table