A **Function Pointer** is a specialized pointer that points to the executable code of a function within the memory's code segment. This is a powerful feature used for implementing "Callbacks," designing flexible APIs, and creating dynamic code execution paths.
The syntax for declaring a function pointer can be tricky. You must specify the return type and the exact parameter types of the function it will point to.
While they might seem complex, function pointers are the backbone of advanced C programming:
switch blocks.qsort() function uses a function pointer to let you define your own comparison logic.Instead of using an if-else chain for operations, we can use an array of function pointers.
| Feature | Data Pointer (int*, char*) | Function Pointer |
|---|---|---|
| Points To | Variable/Data (Stack/Heap) | Executable Code (Code Segment) |
| Primary Use | Modifying data | Invoking logic dynamically |
| Dereferencing | Returns the stored value | Executes the function |
int *ptr(int) is a function returning an int pointer, but int (*ptr)(int) is a function pointer. The parentheses around the *ptr are mandatory!void (*ptr)(int), you cannot assign a function that returns float to it.NULL before calling it, as calling a NULL pointer will cause a segmentation fault.typedef to make function pointer syntax much cleaner. For example, typedef int (*MathFunc)(int, int); allows you to declare pointers simply as MathFunc myPtr;.