Interview Questions
Lambda Expressions · Study material
C++ Lambda Expressions – Interview Questions
1. What is a lambda expression?
An anonymous function object defined inline, optionally capturing variables from the enclosing scope.
2. What is the syntax of a lambda?
[captures](parameters) mutable/constexpr -> return_type { body }.
3. What is the difference between capturing by value and by reference?
By value copies the variable when the lambda is created; by reference refers to the original, seeing later changes and requiring it to stay alive.
4. What do [=] and [&] mean?
Capture every used local variable by value, or by reference, respectively.
5. Why is mutable needed?
The closure's operator() is const by default, so by-value captures cannot be modified without mutable.
6. What is a closure?
The run-time object created from a lambda expression, holding its captured state.
7. What is the type of a lambda?
A unique, unnamed class type generated by the compiler; two identical lambdas still have different types.
8. Can a lambda be converted to a function pointer?
Yes, if it captures nothing.
9. What is a generic lambda?
A lambda with auto parameters (C++14); its operator() is a template.
10. What is an init capture?
[name = expression] (C++14): creates a new member initialised from any expression, e.g. moving a unique_ptr in.
11. What is the difference between [this] and [*this]?
[this] captures the pointer (shares the object, may dangle); [*this] (C++17) captures a copy of the object.
12. How do you write a recursive lambda?
C++23: [](this auto self, int n) { … self(n - 1) … }. Earlier: std::function or pass the lambda as a parameter to itself.
13. When should you use std::function?
When you must store callables of different types behind one signature (callbacks, maps of handlers).
14. What are the costs of std::function?
Type erasure: possible heap allocation for large closures and an indirect call that prevents inlining.
15. Can lambdas be constexpr?
Yes; since C++17 lambdas are implicitly constexpr when possible, and can be marked constexpr explicitly.
16. What happens if a lambda captures a local by reference and is returned?
The reference dangles after the function returns; calling the lambda is undefined behaviour.
17. Can a lambda capture a structured binding?
Yes, since C++20.
18. What is an immediately invoked lambda?
A lambda called right after it is defined, [&] { … }(), often used to initialise const variables.
19. What does a lambda compile into?
A class with captured variables as members and an operator() containing the body.
20. Why are lambdas often faster than function pointers in std::sort?
Each lambda has a unique type, so the algorithm is instantiated for it and the call can be inlined; a function pointer is usually called indirectly.