Function Pointers and Callbacks
A callback lets a general algorithm invoke caller-selected behavior without knowing its implementation.
What is Function Pointers and Callbacks?
A callback lets a general algorithm invoke caller-selected behavior without knowing its implementation.
Pass behavior into another function.
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
main.c
#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
C++
main.cpp
#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.
C
Ownership and cleanup are conventions enforced by the programmer.
C++
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.