Skip to content
UPEEC

Lambda Expressions in C++

Inline anonymous functions that can capture surrounding variables.

Intermediate
Comments 0
int threshold = 100;
auto isHigh = [threshold](int x) { return x > threshold; };   // capture by value
int count = std::count_if(v.begin(), v.end(), isHigh);

button.onPress([&]() { ledOn = !ledOn; });                     // capture by reference

Capture list: [=] copies everything used, [&] references everything, or list variables explicitly (safer). Beware capturing references to locals that will be destroyed before the lambda runs.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.