A function returns [&total] { return total; } where total is a local variable. What happens when the returned lambda is called?
Capture by value ([total]) when a lambda outlives the scope.
Lambda Expressions · Exercise 1 of 4
Twenty multiple-choice questions on C++ lambda expressions: syntax, captures, mutable, init captures, generic lambdas, closure types, std::function and lifetimes. Pick an option to check your answer instantly.
A function returns [&total] { return total; } where total is a local variable. What happens when the returned lambda is called?
Capture by value ([total]) when a lambda outlives the scope.
Must a lambda capture a global or static variable to use it?
Only local (automatic) variables are captured.
When is std::function<void(int)> the right choice?
It erases the type at a small run-time cost; auto and templates keep the exact type.
If no -> type is written, how is a lambda's return type determined?
Returning 1 in one branch and 1.5 in another is an error unless you specify -> double.
What does the compiler generate for a lambda expression?
A lambda is syntactic sugar for a function object.
How does C++23 let a lambda call itself recursively without std::function?
This feature is called "deducing this".
Why is passing a lambda comparator to std::sort typically faster than passing a function pointer?
A function pointer is usually an indirect call the compiler cannot see through.
What did C++20 change about using [=] in a member function?
[=] looked like "copy everything" but actually captured this by pointer.
auto f = [n = 0]() mutable { return ++n; }; – what do three calls to f() return?
n is a member of the closure object, so it keeps its value between calls.
Since C++17, can a lambda be evaluated at compile time, e.g. in a static_assert?
constexpr auto sq = [](int x) { return x * x; }; static_assert(sq(4) == 16);
Timed online tests with instant scores and explanations.