PhilipsRole: Technical LeadSeptember 2026
Interview question
Explain this C++ code line by line. It is intended to print x = 42, but the observed output is another value. Identify the problem and fix it.
#include <iostream>
#include <functional>
std::function<void()> createLambda() {
int x = 42;
return [&x]() {
std::cout << "x = " << x << '\n';
};
}
int main() {
auto lambda = createLambda();
lambda();
return 0;
}
Follow-up questions
- What does std::function<void()> describe, and what happens when lambda() is called?
- What is a lambda expression, and how can the returned lambda be stored in std::function?
- What is the difference between capturing by reference and capturing by value in this example?
- Which object has the void return type: createLambda itself or the returned lambda? What would need to change if the callable signature were changed to return int?