3 ms·
I think it's safe to say that most uses of function pointers in C fall into one of two categories: 1. Objects; 2. Continuations; 3. Callbacks from generic algor
by cperciva 17y ago
I think it's safe to say that most uses of function pointers in C fall into one of two categories: 1. Objects; 2. Continuations; 3. Callbacks from generic algorithms.
A classic example of the first category is in the VFS layer of BSD UNIX: Filesystems provide a standard set of functions for open/read/write/ioctl/stat/close/etc, which all sit in a structure, and the upper layers of the kernel generally invoke those functions without knowing which underlying filesystem is handling them.
A classic example of the second category is event-driven loops: You register "when there's data on socket N, please call this function with this cookie", and the event loop doesn't need to know what the function does or what sort of data you have stored in the cookie. In this way, you can have several different things going on, passing control back and forth by registering "what happens next" and returning.
A classic example of the third category is qsort: There is no requirement for qsort to know what sort of data it is quicksorting, since it invokes the provided callback function whenever it needs to compare two values.
- pgbovine 17y agoisn't your event-driven loop an example of a callback function? i'm no expert on continuations, but i thought they involved somehow packaging up the 'rest of the computation' in some structure and then running it. your example seems to be an ordinary callback.