Advertisement

Lambda Expressions interview questions and answers

12 Lambda Expressions interview questions for C++ roles, each with a model answer, examples and likely follow-ups.

12 questions
Advertisement

12 questions

Q11 Intermediate Save

What is an immediately invoked lambda expression (IILE) and why use it?

An IILE is a lambda that is called right where it's defined, using a trailing (). It's used to initialize a const variable with complex logic, to scope temporary variables, or to run one-off initialization while keeping the result const and the setup contained.
const int config = []{
    int v = load();
    return v * 2;
}();  // invoked immediately
Real-world example
An IILE computes a complex const configuration value inline while keeping helper variables local.
Likely follow-ups
  • How does an IILE help with const? | What are the parentheses at the end for?
Lambda Expressions Const Correctness
Q12 Beginner Save

Can a lambda be recursive?

A lambda can't directly refer to itself by name because it's anonymous and, with auto, its type isn't known during initialization. Workarounds include storing it in a std::function (which can be captured by reference), or in C++23 using the 'deducing this' feature to allow self-reference. Often a named function is simpler for recursion.
std::function<int(int)> fac =
    [&](int n){ return n <= 1 ? 1 : n * fac(n-1); };
Real-world example
A recursive lambda held in std::function computes a factorial within a local scope.
Likely follow-ups
  • Why can't auto lambdas self-refer directly? | What does C++23 add for this?
Lambda Expressions Modern C++

Showing 11–12 of 12