Lambda Expressions in C++: Writing Inline Anonymous Functions
What is Lambda Expressions in C++: Writing Inline Anonymous Functions? Lambda expressions are inline anonymous function objects (closures) defined using the syntax [captures](parameters) -> return_type { body }. The capture clause...
How are lambda expressions defined in C++, what are capture clauses ([=], [&], [this]), and how are they used with STL algorithms?
Explanation & In-Depth Details
```text
┌── Capture Clause (Context access)
│ ┌── Parameter List
│ │ ┌── Trailing Return Type (Optional)
│ │ │ ┌── Function Body
┌─┴─┐ ┌─┴──┐ ┌──┴──┐ ┌───┴────────────────┐
[ x ] (int y) -> int { return x + y; }
```
2. Capture Modes:
- `[]`: Captures nothing.
- `[=]`: Captures all used outer variables by value (read-only copy).
- `[&]`: Captures all used outer variables by reference (can mutate original).
- `[this]`: Captures the current class object pointer.
- `[val = 10]`: Generalized lambda capture (C++14).
Code Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {12, 45, 68, 23, 89, 90, 34};
int threshold = 50;
int matchCount = 0;
// Lambda capturing 'threshold' by value and 'matchCount' by reference
auto countHigh = [&matchCount, threshold](int n) {
if (n > threshold) {
++matchCount;
return true;
}
return false;
};
std::cout << "Numbers above " << threshold << ":\n";
for (int num : numbers) {
if (countHigh(num)) {
std::cout << " - " << num << "\n";
}
}
std::cout << "Total matches: " << matchCount << "\n";
// Generic Lambda (C++14 auto parameter)
auto printTwice = [](auto item) {
std::cout << item << " | " << item << "\n";
};
printTwice("OperateTools");
printTwice(42);
return 0;
}Interview Question & Tips
A: Each lambda expression generates a unique, anonymous closure class type created by the compiler. You can store lambdas using `auto`, function templates, or `std::function<R(Args...)>`.
Q: What does the `mutable` specifier on a lambda do?
A: By default, variables captured by value are `const` inside the lambda body. Adding `mutable` (`[x]() mutable { ++x; }`) allows modifying the local copy of the captured variable.
Best Practices
• Use generic lambdas (`[](auto val)`) for concise polymorphic callables.
• Prefer lambdas over `std::bind` in modern C++ for better compiler optimization and readability.
This study reference for Lambda Expressions in C++: Writing Inline Anonymous Functions is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: