Function Pointers, part 1 - Regular Function Pointer Syntax (Page 2 of 4 )
The function pointer in our quick example points to the address of an ordinary C function. There are no special considerations for us to make in this case.
The code you compile to create your executable takes up a certain space in the computer's memory, where your data and functions will reside during its execution. Just like the data accessible through pointers, we have seen that functions are accessible in the very same way. The only thing a compiler has to know is how to interpret the address to which a pointer is pointing; this is where things can become slightly confusing, as we run into the often odd syntax of function pointers.
Defining and Using Regular Function Pointers
Just like regular pointers, function pointers are variables that need to be declared and defined. In the quick example you saw that inc_one is our function pointer variable, holding the pointer to a function that returns an int and that takes an int as a parameter.
To give you another example, if you declare the following function:
Hopefully you can see a pattern emerging here. The function declaration is basically being repeated, with the function name replaced by a "*varName," and only the types of the parameters are named. The retrieval of the address of a function works just like the address retrieval of a variable; you can use the address dereference operator "&."
Personally, I find the above demonstrated way of defining a function pointer a bit hard to read. When you need more variables to hold pointers to the same function, it can become quite laborious and sensitive to typing errors, too. Not to mention the fact that when the function definition changes, you would have to chase down and change every function pointer pointing to the changed function as well.
So here we will find the use of the typedef keyword very useful:
typedef int (*FncPtr)(int);
When we stick to the example, we can replace the add_one definition with:
FncPtr inc_one = &IncOne;
So you see that it is really easy to declare function pointers. Just as with normal pointers, you either use the pointer directly or you use it by dereferencing the pointer explicitly:
int result1 = inc_one(1);
int result2 = (*inc_one)(1);
Making the function call through a pointer or just the plain way will yield not very noticeable differences. It's quite nice to be able to abstract a function call into a variable, isnít it?