Fundamentals 6 min read

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.

IT Services Circle
IT Services Circle
IT Services Circle
Understanding Function Pointers, Closures, and std::function in C/C++

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
int func(int a) {
    return a + 1;
}

void main() {
    int (*f)(int) = func;
    printf("%p\n", 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.

C++callbackClosurestd::functionfunction pointer
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.