Pointers to Functions in C
So far, you have learned pointers to variables and pointers to arrays.
In this lesson, we take one more powerful step: pointers to functions.
This concept allows a function to be treated like data.
Do not rush. Read slowly. This lesson is simpler than it looks.
Why Do We Need Function Pointers?
Normally, we call functions directly:
add(10, 20);
But sometimes we want to:
- Decide which function to call at runtime
- Pass a function as an argument
- Create flexible and reusable code
This is where function pointers are used.
Function Name Is a Pointer
Just like arrays, a function name represents the address of the function.
That means we can store a function’s address in a pointer.
Basic Syntax of Function Pointer
General format:
return_type (*pointer_name)(parameter_types);
Yes, the syntax looks strange — but the logic is simple.
Simple Example
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*ptr)(int, int);
ptr = add;
printf("%d", ptr(5, 3));
return 0;
}
Explanation:
addis the functionptrstores its addressptr(5,3)calls the function
Calling Function Using Pointer
These two calls are equivalent:
add(5, 3);
ptr(5, 3);
The compiler treats both the same.
Real-World Example
Imagine a remote control:
- Buttons do not perform work
- They point to actions
Function pointers work the same way. They point to different functions dynamically.
Using Function Pointers with Multiple Functions
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int main() {
int (*operation)(int, int);
operation = add;
printf("Add: %d\n", operation(10, 5));
operation = subtract;
printf("Subtract: %d\n", operation(10, 5));
return 0;
}
Same pointer, different behavior.
Where Are Function Pointers Used?
- Callbacks
- Event handling
- Sorting algorithms
- Menu-driven programs
- Operating systems
Common Mistakes
- Wrong function signature
- Missing parentheses in pointer declaration
- Confusing function call and pointer call
Mini Practice
- Create two functions (multiply, divide)
- Use a function pointer to call both
- Print results
Quick Quiz
Q1. What does a function pointer store?
Address of a function.
Q2. Why are parentheses important in function pointers?
They ensure correct binding of pointer to function signature.
Q3. Can a function pointer point to different functions?
Yes, as long as signatures match.
Q4. Where are function pointers commonly used?
Callbacks, menus, event systems, sorting.
Q5. Are function pointers advanced or basic?
They are fundamental for advanced C programming.