Sunday, May 15, 2011

Function pointers in C

This time I'll tackle a C language construct. While C may be a very shallow abstraction of a computational machine, it still has a lot of punch to offer.

Functions are sections of code that can be invoked. Sometimes we do know what the function looks like before we invoke it, but we don't have a definition for it at compile time (a function imported from a shared dynamic library for example). Function pointers fit for this use case perfectly.

In the following code snippet I show a very simple example of using function pointers.


#include "stdlib.h"

typedef int (*intfun) ();

int u(){
return 1;
}

int v(){
return 2;
}

int main(){
intfun f = &u;
printf("Hello there %i\n", (*f)());
printf("Hello there %i\n", f());
f = v;
printf("Hello there %i\n", (*f)());
printf("Hello there %i\n", f());
return 0;
}


The typedef defines that `intfun` is a type, such that if any `a` was of type `intfun`, then dereferencing `a` and calling it would be the same as calling a function that takes no parameters and returns `int`.

In the code snippet above (which I so far tried compiling in MinGW on Windows), `f` is declared to be a variable of type `intptr` and it is initialized by passing it the address of function `u`. To call `u` through `f`, you can dereference `f` and then pass it an empty parameter list. However, the C compiler is smart enough to dereference the function pointer implicitly if it was invoked with a parameter list.
We can also see this magic happening when assigning values to `f`. We don't need to use the address of operator with `v` to assign it to `f`.

In future posts I'll show how it is possible to use function pointers to get rid of annoying large switch block statements that scream "procedural".

1 comment:

  1. > large switch block statements that scream "procedural".

    Who still uses that ??? xD

    ReplyDelete