Function Pointers and Callbacks
Pass behavior into another function.
What is Function Pointers and Callbacks?
A callback lets a general algorithm invoke caller-selected behavior without knowing its implementation.
Important points
- Every pointer must refer to a live compatible object or be null.
- Pair each owned allocation with exactly one release.
- Prefer clear ownership and const-correct interfaces.
C and C++ code examples
#include <stdio.h>
int square(int value) { return value * value; }
int apply(int value, int (*operation)(int)) { return operation(value); }
int main(void) {
printf("%d\n", apply(6, square));
return 0;
}
36
#include <functional>
#include <iostream>
int apply(int value, const std::function<int(int)>& operation) {
return operation(value);
}
int main() {
int factor = 6;
std::cout << apply(factor, [](int value) { return value * value; }) << '\n';
}
36
C and C++ comparison
C uses an explicit function-pointer type. C++ lambdas and std::function can hold richer callable objects, although a template is preferable in performance-sensitive generic code.
Ownership and cleanup are conventions enforced by the programmer.
Containers and RAII types can encode ownership and cleanup in object lifetimes.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Test null and allocation-failure paths.
- Run with AddressSanitizer and UndefinedBehaviorSanitizer.
- Document whether every pointer owns or only observes its object.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges