I understand I can use pointers for functions.
Can someone explain why one would use them, and how? Short example code would be very helpful to me.
For code, check out qrdl's response to state machines tutorials.
I've used a variant of his method to implement a a menu for an LCD display I have on a board. Very very useful, makes the coding much cleaner and easier to read. Using function pointers makes expanding the number, names and ordering of menus very easy, and hides all those details from the higher level calling function that just sees 'hey, I write to the LCD here.'
You use a function pointer when you need to give a callback method. One of the classic example is to register signal handlers - which function will be called when your program gets SIGTERM (Ctrl-C)
Here is another example:
// The four arithmetic operations ... one of these functions is selected
// at runtime with a switch or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
You can learn more about function pointers here http://www.newty.de/fpt/index.html
If you are more familiar with object-oriented languages, you can think of it as C's way to implement the strategy design pattern.
Callbacks. I make an asynchronous call to a chunk of code and want it to let me know when it finishes, I can send it a function pointer to call once it's done.
I'm surprised no one mentioned "state machines". Function pointers are a very common way to implement state machines for tasks such as parsing. See for example: link.
Another usage for pointers is iterating lists or arrays.
One quite common use case is a callback function. For example if you load something from a DB you can implement your loading function so that it reports the progress to a callback function. This can be done with function pointers.