Function callbacks in C

Ever since I started programming in Javascript, and doing asynchronous function calls, I’ve found myself to be addicted to passing functions as parameters.

I do it a lot in python and php, it’s very easy to do this on all these dynamic typed languages.

I never had this concept of passing functions as parameters, or pointers to functions as parameters when I was a kid in school and we were doing stuff in C or Pascal, I’d deal with it with ifs and switches.

So, this afternoon I decided to read a little bit and give it a try in C.

Here’s some code for future reference If I ever need it, it’s pretty easy.

void this() { printf("Thisn"); }
void that() { printf("Thatn"); }

int sum(int x, int y) {	return x+y; }

int mul(int x, int y) { return x*y; }

//Function that takes a callback that uses no parameters
void callanother(void (*callback)()) {

//Function that takes a callback that
//takes 2 int parameters and returns int
int callComplexCallback(int (*callback)(),int a, int b) {
  return (*callback)(a,b);

int main (int argc, char** argv) {


  int w = 20;
  int h = 30;


  //this also works

  return 0;

The output is this:

~$ ./a.out 


The whole trick is how you define the function that will take the other function as a parameter.

If you have a function:

void whatever();

The function that’s supposed to use “whatever()” like-functions should look:

void useWhateverLikeFunctions(void (*f)()) {

If you have a callback function that needs parameters, then you define the caller as:

void callerFunction(void (*f),int paramA, int* paramB, char paramC) {

Then you’d use the function

void someCallback(int a, int* b, char c);


I know this is the oldest thing in the world to C programmers, but it never crossed my mind before, so here it is for my own personal reference, I hope it serves others.