Objective
This demo provides a working example of function pointers in action. Function pointers are not frequently used in C programming (perhaps due to their strange syntax), but can be extremely useful in some circumstances.
Software Tools
Tool | About | Installers |
Installation
Instructions |
||
---|---|---|---|---|---|
Windows | Linux | Mac OSX | |||
MPLAB® X
Integrated Development Environment |
| | | | |
MPLAB® XC16
C Compiler |
| | | | |
Exercise Files
File | Download |
Installation
Instructions |
||
---|---|---|---|---|
Windows | Linux | Mac OSX | ||
Project and Source Files
|
| | | |
Procedure
1
Open the Project
Start MPLAB® X IDE, then click on the Open Project
Navigate to the folder where you saved the exercise files for this class.
Click on the Lab13.X folder.Select Open Project

2
Debug Project
Click on the Debug Project
Click on the Continue

Click on the Halt

3
What just happened?
As was done earlier in the class, we opened a pre-configured MPLAB X IDE workspace with a complete, working program. We then compiled the code and ran it long enough for it to complete its task. This program uses a function pointer to pass the address of a mathematical function to another function that will compute its integral.
The integral example was adapted from one published on Wikipedia at: http://en.wikipedia.org/wiki/Function_pointer. The integral function takes three parameters: the upper and lower bounds of the integral, and the address of the function that it is to evaluate. The function’s header looks like:
float integral(float a, float b, float (*f)(float))
Note that the third parameter is defined as a function pointer. When we call this function, we only need to provide the name of the function we want to integrate. For example:
y2 = integral(0, 1, xsquared);
The function xsquared() is a simple mathematical function defined as:
float xsquared(float x)
{
return (x * x);
}
There are other functions that may be passed to the integral() function as well.
Results
4
End Debug Session
Clear the UART 1 Window - put the cursor in the UART 1 Window then enter Ctrl +L. This will clear the UART 1 Window before your next simulation.End the Simulation Session by clicking the Finish Debugger Session

Then CLOSE the Project by right-clicking on Lab02 from the Projects Window and then selecting Close.
Conclusions
Function pointers, while not frequently used, can provide a very convenient mechanism for passing a function to another function.
Many other possible applications exist
- Jump tables
- Accommodating multiple calling conventions
- Callback functions (used in Windows™)
- Call different versions of a function under different circumstances