Lesson 21: Function pointers
Not only variables live in memory — function code does too, so functions also have addresses. A function pointer stores such an address: int (*op)(int, int); — and the parentheses around (*op) are critical; without them it's a completely different declaration. After op = add; you can call op(3, 4) j
A function pointer is a speed-dial button on a phone: the button can't talk by itself, it just stores 'whom to call'. You can assign it to mom or to the pizzeria — pressing it (calling) reaches whoever is stored there right now.
- function pointer
- A variable storing a function's address — you can call through it and change what it points at.
- declaration anatomy int (*op)(int, int);
- op is a pointer to a function taking two ints and returning int. The parentheses around (*op) are the critical part.
- function name as address
- A function name without parentheses (like add) is its address — that's why op = add; works.
- callback
- A function passed as a pointer to another function, to be invoked at the right moment.
- qsort's comparator
- qsort receives a pointer to a comparison function — that's how it can sort any type.