⚙️ C++ Beginner

What are lambda expressions in C++?

Why Interviewers Ask This

This is a classic screening question for C++ roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

Lambda expressions (C++11) are anonymous inline functions — closures that can capture variables from the surrounding scope. They eliminate the need for named helper functions for short, one-use operations. Syntax: [capture](parameters) -> return_type { body }. Examples: // Basic lambda auto square = [](int x) { return x * x; }; std::cout << square(5); // 25 // Capture by value (copy): int base = 10; auto addBase = [base](int x) { return x + base; }; // Capture by reference: auto addToBase = [&base](int x) { base += x; }; // Capture all by value: auto f = [=]() { return base * 2; }; // Capture all by ref: auto g = [&]() { base = 0; }; // Capture specific mix: auto h = [base, &total](int x) { total += base + x; };. With STL algorithms: std::vector<int> v = {5, 3, 8, 1, 9, 2}; std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // Descending auto sum = std::accumulate(v.begin(), v.end(), 0, [](int acc, int x) { return acc + x; }); auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 5; });. Generic lambda (C++14): auto print = [](auto x) { std::cout << x; }; print(42); print("hello");. Immediately invoked: int result = [](int a, int b) { return a + b; }(3, 4); // 7. Mutable: by default, captured values are const in the lambda body. Use mutable: auto f = [count = 0]() mutable { return ++count; };. Under the hood: compiler generates an unnamed closure class with operator() for each lambda.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real C++ project.