Preslav's Thoughts and Ramblings

C/C++ Tips for JavaScript Geeks: The Function Pointer

22 July 2012 | c++, cpp, javascript, tip

In JavaScript, the function is a first class object. This allows us to pass functions as parameters to other functions, and execute them. Very much like:

var p = function() {  
   console.log("Executing the callback function");
}

var c = function(callBack) {  
   console.log("Executing the wrapper function");
}

c(p);  

C/C++ does not treat functions as first-class objects. However, unlike Java, which hides all the pointer complexity away from the programmer, C/C++ allows you to deal with pointers. On a pointer level, a concept exists, called a function pointer. It allows us to pass pointers to functions to other functions, and then execute them within those functions. Nice isn’t it? Check out the following code:

#include <iostream>
using namespace std;

void theWrapperFunction(int (*fnc) ()) {  
    cout << fnc();
}

int theCallBackFunction() {  
    return 12345;
}

//here starts the show
int main (int argc, char * const argv[]) {  
    theWrapperFunction(theCallBackFunction)
}

As you may have guessed, the result will output 12345. The signature int (*fnc) () in our case, tells the compiler that we need a pointer to a function that returns an integer, and has no params. It is a bit too cumbersome to remember every time, right? Luckily, C/C++ has comp with the keyword typedef, which allows us to encapsulate it within a type, and from then onwards, use the type name.