C++ Lambdas and C Closures
A lambda creates an unnamed callable object and may capture local state; C callbacks need context passed explicitly.
What is C++ Lambdas and C Closures?
A lambda creates an unnamed callable object and may capture local state; C callbacks need context passed explicitly.
Capture context for a callback.
Important points
- Understand the C mechanism before comparing the C++ abstraction.
- Use RAII and value semantics to express ownership.
- Prefer type-safe compile-time abstractions over macros and casts.
C and C++ code examples
main.c
#include <stdio.h>
int above(int value, void *context) {
return value > *(int *)context;
}
int main(void) {
int values[] = {2, 7, 4, 9};
int threshold = 5;
int count = 0;
for (int index = 0; index < 4; ++index) {
count += above(values[index], &threshold);
}
printf("%d\n", count);
}
2
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector values{2, 7, 4, 9};
int threshold = 5;
auto above = [threshold](int value) {
return value > threshold;
};
std::cout << std::count_if(values.begin(), values.end(), above)
<< '\n';
}
2
C and C++ comparison
The C function receives a void pointer and casts it to known context. The C++ lambda captures threshold by value, keeping type information without manual casting.
C
C uses naming conventions, callbacks, macros, and explicit context structures.
C++
Language features provide scoped, type-safe, and often zero-overhead abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Write the C mechanism before the C++ abstraction.
- Remove manual cleanup with RAII.
- Check whether the abstraction adds allocations or virtual dispatch.