More on function pointers
A function pointer is a pointer to a function, i.e. it’s a variable (a pointer) but instead of pointing to some data, it is assigned to a function. Most importantly, the compiler checks that the function you are assigning is compatible to that pointer. This is so, as I discussed earlier that when the function is executed, it correctly retrieves any parameters.
Here’s how you create a function pointer. Let’s start with a function that adds 1 to the input value.
int getValue(int x) {
return n + 1;
};
This passes in x and returns an int. Let’s create a pointer to this function and this is the full program.
#include <stdio.h>
int getValue(int n) {
return n + 1;
}
typedef int (*getValueFn)(int);
int main()
{
getValueFn f = &getValue;
printf( "Value of getValue = %d\n",f(1));
}
It’s as simple as that. The complicated bit is turning the function signature into the typedef. Start with the function name. Put it in brackets and add a * at the start, and make the name different to the function you are assigning. It’s a new type. So getValue becomes (*getValueFn).
Now add on the return type at the start int and the parameters at the end (int n), but throw away the name n, we only need the type and you get int (*getValueFn)(int);
Finally add typedef, cook for 30 microseconds and you’re done! In the line getValueFn f = &getValue;
I’ve declared an instance of the type f and assigned to it the address of getValue. That gets called with a value f(1) and in this case returns 2.
It’s also good practice to check that the instance variable is not null before you call it.

In the Empire game (yes, just one last mention!) during the map generation the program counts up the size of individual islands and sea areas. This is don by recursion and quite useful. Otherwise, the usual place you see recursion mentioned is in calculating factorials and Fibonacci sequences.
This post refers to the c sources in the AboutEmpire.zip file in the
Nuklear

Back in 2012/2013 I was writing the C/C++/C# column for About.com and I was doing games tutorials with SDL. This is an Empire type game, much like the Z80 game I mentioned in yesterday’s post except coded in C and with hexagons instead of squares.
Part of the reason is SDL which is a wonderful library and whose potential I have barely touched. I used to be an 8-bit games developer back in the 1980s, writing games for CBM-64, ZX Spectrum, MSX and Amstrad CPC-464.