C Callbacks

Jan 16, 2019 08:52 · 169 words · 1 minute read

In project 1 (of operating systems), we need to use C function pointers and callbacks as part of the HTTP (like) multi-threaded client that we are writing. And although I understand the syntax of function pointers and callbacks, I’ve always wondered when and why we should use them. So what I did was hop in the #project1 slack channel, asking someone to explain the why behind callbacks (despite me using them when I wrote NodeJS code, where you cannot get away with writing asynchronous code).

And several TA (teacher assistants) chimed in and the answer really boils down to offering the caller (of your library or client) to execute their own code when some event occurs. This is common in event-driven model, where a client wants y to happen when x event occurs.

In other words, instead of hardcoding a bunch of logic inside of your client, you offer flexibility (to the caller), allowing them to perform some action when some event is detected (by the client library).

Neato.