Understanding Function Pointers, Closures, and std::function in C/C++
This article explains how C/C++ function pointers work, demonstrates their compiled address, shows why they lack context, introduces a closure struct to bundle code with data, and relates this pattern to C++'s std::function for storing callables with captured environment.
In C/C++ a pointer can refer to a block of code; such a pointer is called a function pointer. The article starts with a simple example where a function func returns its argument plus one, and a pointer f is assigned to it and printed.
#include <stdio.h>
int func(int a) {
return a + 1;
}
void main() {
int (*f)(int) = func;
printf("%p
", f);
}Compiling the program and inspecting the generated assembly shows that func resides at address 0x400526. Running the executable prints this address, illustrating that a function pointer is essentially a pointer to executable code.
The article then points out that a plain function pointer cannot capture any surrounding context (data the function needs). To pass both code and data, a closure struct is defined:
typedef void (*func)(int);
struct closure {
func f;
int arg;
};The struct contains two members: a pointer to the code and a variable holding the data (the context). By assigning the function pointer in module A and the data in module B, the closure can be passed to module C, which can invoke the code with its associated data:
void run(struct functor func) {
func->f(func->arg);
}This pattern mirrors the purpose of C++'s std::function, which stores a callable object together with any captured context, allowing it to be invoked later. Unlike raw function pointers, std::function can hold lambdas, bind expressions, or member functions that require a this pointer, effectively providing the missing context capture capability.
Thus, the article demonstrates how function pointers work, why they lack context, and how defining a closure struct or using std::function solves this limitation, enabling more flexible callback mechanisms in C and C++ programs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
