What are Lambda Expressions in C++?
Learn C++ lambda expressions: syntax, capture lists by value and reference, mutable, and using closures with STL algorithms, with clear code examples.
Expected Interview Answer
A lambda expression in C++ is an anonymous, inline function object you can define right where it is used, most often passed to algorithms or stored in a callable.
Introduced in C++11, a lambda has the form [captures](params) -> ret { body }. The capture list controls which surrounding variables are visible inside the body and whether they are captured by value ([=], copy) or by reference ([&]). The compiler turns each lambda into a unique unnamed closure type with an overloaded operator(). Adding mutable lets a by-value capture be modified, and later standards added generic (auto) parameters and constexpr lambdas.
- Keeps short logic local to where it is used
- Avoids writing separate named functor structs
- Captures local state cleanly and explicitly
- Works seamlessly with STL algorithms
- Can be inlined by the compiler for speed
AI Mentor Explanation
A lambda is like a captain's on-the-spot field-placement instruction shouted for a single over rather than a permanent team rule. It captures the current match situation — the batter, the score, the pitch — and acts on it immediately, then is forgotten, exactly as a lambda captures nearby variables and does its small job right where it is needed.
Step-by-Step Explanation
Step 1
Write the capture list
Use [] for none, [=] for by-value, [&] for by-reference, or name specific variables like [x, &y].
Step 2
Declare parameters
Add a parameter list in parentheses just like a normal function, e.g. (int a, int b).
Step 3
Optionally specify the return type
Add -> Type when the compiler cannot deduce it; otherwise it is inferred from the return statements.
Step 4
Write the body
Put the logic in braces; it runs when the closure's operator() is invoked.
Step 5
Use or store the lambda
Pass it to an STL algorithm, invoke it immediately, or hold it in auto or std::function.
What Interviewer Expects
- Correct lambda syntax including the capture list
- Difference between capture by value and by reference
- Knowing a lambda compiles to a unique closure type
- When mutable is required
- Practical use with STL algorithms like std::sort
Common Mistakes
- Capturing a local by reference that outlives the lambda's use, causing a dangling reference
- Assuming [=] lets you modify the copies without mutable
- Confusing the capture list with the parameter list
- Overusing std::function when auto would avoid heap allocation overhead
Best Answer (HR Friendly)
“A lambda in C++ is a small function you can write directly inside your code without giving it a name, usually to pass quick logic to another function. It can remember values from the surrounding code, which makes it handy for short, one-off tasks like sorting or filtering a list.”
Code Example
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums{5, 2, 8, 1, 9};
int threshold = 4;
// Sort descending with an inline lambda
std::sort(nums.begin(), nums.end(),
[](int a, int b) { return a > b; });
// Capture 'threshold' by value and count matches
int count = std::count_if(nums.begin(), nums.end(),
[threshold](int n) { return n > threshold; });
std::cout << count << " values above " << threshold << '\n';
return 0;
}Follow-up Questions
- What is the difference between capturing by value and by reference?
- When do you need the mutable keyword in a lambda?
- How does a lambda differ from std::function and a raw function pointer?
- What is a generic lambda introduced in C++14?
- Can a lambda be constexpr, and what does that enable?
MCQ Practice
1. What does the capture list [&] mean in a C++ lambda?
[&] captures every automatic variable used in the body by reference, so changes affect the originals.
2. Which keyword allows a by-value captured variable to be modified inside the lambda body?
By default the generated operator() is const; marking the lambda mutable lets it modify its by-value copies.
3. What type does the compiler generate for each lambda expression?
Every lambda produces a distinct compiler-generated closure class with an overloaded function-call operator.
Flash Cards
What is a lambda expression? — An anonymous inline function object with the form [captures](params) -> ret { body }.
[=] vs [&] capture — [=] captures used locals by value (copies); [&] captures them by reference.
Why use mutable? — It removes the implicit const on operator(), allowing modification of by-value captures.
What type is a lambda? — A unique, compiler-generated unnamed closure type with an overloaded operator().