C++ Lambda Expressions Quiz

C++
0 Passed
0% acceptance

40 in-depth questions covering C++ lambda expressions, capture lists, mutable lambdas, returning lambdas, storing lambdas in std::function, and lambda recursion techniques — with 16 code examples to solidify understanding.

40 Questions
~80 minutes
1

Question 1

What is a lambda expression in C++?

A
An anonymous function object that can capture variables from its surrounding scope and be used inline
B
A named function
C
A class definition
D
A variable declaration
2

Question 2

What is the difference between capture by value and capture by reference?

cpp
int x = 42;
auto value_capture = [x]() { return x; };     // Copy of x
x = 100;  // Doesn't affect lambda

int y = 42;
auto ref_capture = [&y]() { return y; };      // Reference to y
y = 100;   // Affects lambda result
A
Value capture copies variables at lambda creation time, reference capture creates references that reflect later changes
B
They are identical capture modes
C
Reference capture copies variables
D
Value capture creates references
3

Question 3

What is a mutable lambda?

cpp
int x = 0;
auto lambda = [x]() mutable { return ++x; }; // Can modify copy

// Without mutable: error - cannot modify const copy
// auto bad_lambda = [x]() { return ++x; };
A
A lambda that can modify variables captured by value, allowing stateful behavior in otherwise stateless functions
B
A lambda that can be changed after creation
C
A lambda that captures by reference
D
A lambda that cannot capture variables
4

Question 4

What is std::function and how does it relate to lambdas?

cpp
#include <functional>

std::function<int(int)> func = [](int x) { return x * 2; };
// Can store any callable with matching signature

func(5); // Returns 10
A
A type-erased wrapper for callable objects including lambdas, function pointers, and functors, enabling storage and passing of different callable types with the same signature
B
A lambda expression
C
A function pointer
D
A class template
5

Question 5

What is capture by default?

cpp
int x = 1, y = 2, z = 3;
auto capture_all_value = [=]() { return x + y + z; };  // All by value
auto capture_all_ref = [&]() { return x + y + z; };    // All by reference

auto mixed = [x, &y, z]() { return x + y + z; };       // Mixed capture
A
Default capture mode ([=] for value, [&] for reference) that captures all accessible variables in the scope with the specified method
B
Capturing no variables
C
Capturing only local variables
D
Capturing only global variables
6

Question 6

What is a generic lambda?

cpp
auto generic_lambda = [](auto x, auto y) { return x + y; };
// Works with different types
generic_lambda(1, 2);       // int + int
generic_lambda(1.5, 2.5);   // double + double
generic_lambda("a", "b"); // const char* + const char*
A
A lambda that uses auto parameters to accept any type, enabling template-like behavior for inline functions
B
A lambda that only works with one type
C
A lambda that requires template syntax
D
A lambda that cannot be generic
7

Question 7

What is the difference between lambda and function object (functor)?

cpp
auto lambda = [](int x) { return x * 2; };

class Functor {
public:
    int operator()(int x) const { return x * 2; }
};

Functor functor;
// Both callable: lambda(5), functor(5)
A
Lambda is anonymous inline function, functor is class with operator() that can maintain state and be reused
B
They are identical concepts
C
Functors are anonymous
D
Lambdas maintain state
8

Question 8

What is init capture (C++14)?

cpp
int x = 42;
auto lambda = [y = x * 2]() { return y; }; // Initialize capture
// Equivalent to: int y = x * 2; then [y]

// Can also move objects:
std::unique_ptr<int> ptr = std::make_unique<int>(42);
auto move_lambda = [p = std::move(ptr)]() { return *p; };
A
A capture that allows initializing new variables in the capture list with arbitrary expressions, enabling move capture and computed values
B
Capturing variables by value
C
Capturing variables by reference
D
Not capturing any variables
9

Question 9

What is lambda recursion and how is it implemented?

cpp
std::function<int(int)> fibonacci = [&](int n) -> int {
    if (n <= 1) return n;
    return fibonacci(n-1) + fibonacci(n-2); // Recursive call
};

// Alternative with Y combinator (advanced)
auto Y = [](auto f) {
    return [f](auto x) { return f(f, x); }; // Not shown fully
};
A
Lambdas calling themselves, implemented by storing lambda in std::function to create named recursive callable
B
Lambdas that cannot recurse
C
Lambdas that call other functions
D
Lambdas that repeat operations
10

Question 10

What is the difference between lambda and regular function return types?

cpp
auto explicit_return = [](int x) -> double { return x * 2.5; };

auto auto_return = [](int x) { return x * 2.5; }; // Returns double

auto reference_return = [](int& x) -> int& { return x; }; // Reference
A
Lambda return type can be explicit (-> Type) or auto-deduced, allowing reference returns and complex type deduction
B
They are identical in return type handling
C
Regular functions have auto-deduction
D
Lambdas cannot return references
11

Question 11

What is a constexpr lambda (C++17)?

cpp
constexpr auto square = [](int x) constexpr { return x * x; };

constexpr int result = square(5); // Compile-time evaluation

static_assert(square(5) == 25); // Compile-time assertion
A
A lambda that can be evaluated at compile-time when given constant expressions, enabling metaprogramming and compile-time computation
B
A lambda that is always evaluated at runtime
C
A lambda that cannot be constexpr
D
A lambda that requires runtime evaluation
12

Question 12

What is the difference between lambda capture and parameter passing?

cpp
int factor = 2;
auto capture_lambda = [factor](int x) { return x * factor; }; // Capture

auto param_lambda = [](int x, int factor) { return x * factor; }; // Parameter

// Usage:
capture_lambda(5);     // Uses captured factor
param_lambda(5, 3);    // Uses passed factor
A
Capture binds variables at lambda creation time, parameters are provided at call time allowing different values per call
B
They are identical mechanisms
C
Parameters bind at creation time
D
Capture allows different values per call
13

Question 13

What is lambda composition?

cpp
auto add = [](int x, int y) { return x + y; };
auto multiply = [](int x, int y) { return x * y; };

auto add_then_multiply = [add, multiply](int x, int y, int z) {
    return multiply(add(x, y), z);
};

// Or using std::function composition
std::function<int(int)> twice = [](int x) { return x * 2; };
std::function<int(int)> plus_three = [](int x) { return x + 3; };
A
Combining multiple lambdas to create complex operations, either by capturing lambdas or using functional composition patterns
B
Creating single large lambdas
C
Splitting lambdas into smaller parts
D
Converting lambdas to functions
14

Question 14

What is the difference between lambda and bind expression?

cpp
using namespace std::placeholders;
auto lambda_add = [](int x, int y) { return x + y; };

auto bind_add = std::bind([](int x, int y) { return x + y; }, _1, _2);
// Or: auto bind_add = std::bind(std::plus<int>(), _1, _2);

// Both callable: lambda_add(1, 2), bind_add(1, 2)
A
Lambda is inline function definition, bind creates callable by binding arguments to existing functions with placeholder syntax
B
They are identical approaches
C
Bind creates inline functions
D
Lambda binds arguments
15

Question 15

What is a lambda with variadic parameters?

cpp
template<typename... Args>
auto make_logger = [](Args&&... args) {
    // Log all arguments
    ((std::cout << args << " "), ...);
    std::cout << std::endl;
};

make_logger("Hello", 42, 3.14); // Variadic lambda
A
A lambda that accepts variable number of arguments using parameter packs, enabling generic callable objects with any number of parameters
B
A lambda with fixed parameters
C
A lambda that cannot have parameters
D
A lambda with optional parameters
16

Question 16

What is the difference between lambda closure and function closure?

A
Lambda closure captures variables from surrounding scope, function closure refers to functions that capture their environment in functional programming languages
B
They are identical concepts
C
Function closure captures in C++
D
Lambda closure is different from capturing
17

Question 17

What is lambda lifetime and capture lifetime?

cpp
auto make_lambda() {
    int local = 42;
    return [&local]() { return local; }; // Dangling reference!
}

auto lambda = make_lambda();
// lambda() is undefined behavior - local destroyed
A
Lambda object lifetime is independent of captures, but captured references must not outlive their referenced objects
B
They are identical lifetimes
C
Lambda lifetime depends on captures
D
Captured references can outlive objects
18

Question 18

What is the difference between lambda and inline function?

A
Lambda is anonymous function object with captures, inline function is named function that may be inlined by compiler
B
They are identical concepts
C
Inline functions have captures
D
Lambdas are named
19

Question 19

What is lambda template (C++20)?

cpp
auto lambda_template = []<typename T>(T value) {
    return value;
};

lambda_template(42);     // T = int
lambda_template("hello"); // T = const char*

// Equivalent to template lambda with auto
A
A lambda with explicit template parameters, providing more control over template argument deduction than auto parameters
B
A lambda without templates
C
A lambda that requires explicit types
D
A lambda that cannot be templated
20

Question 20

What is the difference between lambda copy and lambda move?

cpp
auto lambda = [x = std::make_unique<int>(42)]() { return *x; };

auto copy1 = lambda; // Copy: both point to same int
copy1(); // OK

std::unique_ptr<int> p = std::make_unique<int>(42);
auto move_lambda = [x = std::move(p)]() { return *x; }; // Move
A
Lambda copy duplicates captures, lambda move transfers ownership of move-only captures like unique_ptr
B
They are identical operations
C
Lambda move duplicates captures
D
Lambda copy transfers ownership
21

Question 21

What is the difference between lambda and coroutine?

A
Lambda is function object executed normally, coroutine can suspend and resume execution at specific points
B
They are identical execution models
C
Coroutines are function objects
D
Lambdas can suspend execution
22

Question 22

What is lambda hoisting?

cpp
auto lambda = []() {
    // Lambda defined at global scope
    return 42;
};

void func() {
    // Lambda accessible here
    lambda();
}
A
Defining lambdas at appropriate scope level to maximize their accessibility and lifetime
B
Moving lambdas to different scopes
C
Converting lambdas to global functions
D
Removing lambdas from code
23

Question 23

What is the difference between lambda and function try block?

cpp
auto safe_lambda = []() {
    try {
        risky_operation();
    } catch (...) {
        handle_error();
    }
};

// Function try block:
void func() try {
    risky_operation();
} catch (...) {
    handle_error();
}
A
Lambda try block handles exceptions within lambda body, function try block handles exceptions during initialization and in constructor body
B
They are identical exception handling
C
Function try block is for lambdas
D
Lambda try block handles initialization
24

Question 24

What is lambda memoization?

cpp
auto fibonacci = [](int n) {
    static std::map<int, int> cache;
    if (cache.count(n)) return cache[n];
    if (n <= 1) return cache[n] = n;
    return cache[n] = fibonacci(n-1) + fibonacci(n-2);
};
A
Caching computation results in lambda to avoid redundant calculations, using static variables to persist state across calls
B
Forgetting previous computations
C
Removing cache from lambda
D
Making lambda forgetful
25

Question 25

What is the difference between lambda and functor performance?

A
Lambda has zero overhead for empty capture lists, functor may have virtual function overhead and larger size
B
They have identical performance
C
Functors are always faster
D
Lambdas have virtual function overhead
26

Question 26

What is lambda currying?

cpp
auto add = [](int x) {
    return [x](int y) { return x + y; };
};

auto add_five = add(5);     // Returns lambda
int result = add_five(3);   // 8

// Or more generally:
auto curry = [](auto f, auto x) {
    return [f, x](auto y) { return f(x, y); };
};
A
Transforming multi-argument function into sequence of single-argument functions by returning lambdas that capture partial arguments
B
Converting functions to single argument
C
Removing arguments from functions
D
Making functions take more arguments
27

Question 27

What is the difference between lambda and method reference?

A
Lambda is anonymous function definition, method reference is syntax to refer to existing methods in functional programming languages
B
They are identical concepts
C
Method reference is C++ syntax
D
Lambda refers to existing methods
28

Question 28

What is lambda lifting?

cpp
auto lambda = [x = 42]() { return x; };
// Lambda captures x by value

// After lifting (conceptual):
struct Lambda {
    int x;
    int operator()() const { return x; }
};
// Compiler generates equivalent class
A
Compiler transformation that converts lambda with captures into functor class with captured variables as members
B
Moving lambda to different scopes
C
Removing captures from lambda
D
Converting lambda to function
29

Question 29

What is the difference between lambda and block scope?

cpp
{
    int x = 42;
    auto lambda = [x]() { return x; }; // Captures x
    lambda(); // Can use x
} // x destroyed, lambda still holds copy

// vs block scope variable:
{
    int y = 42;
} // y destroyed immediately
A
Lambda extends lifetime of captured variables, block scope variables are destroyed at block end
B
They are identical scoping rules
C
Block scope extends lambda lifetime
D
Lambda destroys variables immediately
30

Question 30

What is lambda inlining?

A
Compiler optimization that expands lambda body inline at call site, eliminating function call overhead for small lambdas
B
Converting lambda to inline function
C
Preventing lambda inlining
D
Making lambda calls slower
31

Question 31

What is the difference between lambda and delegate?

A
Lambda is anonymous function object, delegate is type-safe function pointer in languages like C# that can reference methods
B
They are identical concepts
C
Delegate is C++ feature
D
Lambda is type-safe pointer
32

Question 32

What is lambda partial application?

cpp
auto multiply = [](int x, int y) { return x * y; };

auto double_func = [multiply](int x) { return multiply(2, x); };
// Partially applies first argument

double_func(5); // Returns 10
A
Creating new lambda that fixes some arguments of original function, leaving others to be provided later
B
Applying all arguments at once
C
Removing arguments from function
D
Making function take more arguments
33

Question 33

What is the difference between lambda and function object size?

A
Lambda size depends on captured variables, function object size includes all member variables and virtual table if polymorphic
B
They have identical sizes
C
Function objects are always smaller
D
Lambdas include virtual tables
34

Question 34

What is lambda coroutine (C++20)?

cpp
auto generator = []() -> std::generator<int> {
    for (int i = 0; i < 10; ++i) {
        co_yield i; // Suspend and return value
    }
};

for (int value : generator()) {
    std::cout << value << " ";
}
A
A lambda that uses coroutines (co_yield, co_return) to create generators or async functions with suspend/resume capability
B
A lambda that runs continuously
C
A lambda without suspension
D
A lambda that cannot yield
35

Question 35

What is the difference between lambda and macro?

A
Lambda is type-safe function object with proper scoping, macro is text substitution without type checking or scoping rules
B
They are identical text processing
C
Macros are type-safe
D
Lambdas are text substitution
36

Question 36

What is lambda statefulness?

cpp
auto counter = [count = 0]() mutable {
    return ++count; // Modifies captured state
};

counter(); // 1
counter(); // 2
counter(); // 3
A
Lambda ability to maintain state across calls through mutable captures, enabling closures with persistent data
B
Lambda that has no state
C
Lambda that forgets state
D
Lambda that cannot maintain state
37

Question 37

What is the difference between lambda and bind performance?

A
Lambda has zero overhead for direct calls, std::bind creates function object with argument forwarding overhead
B
They have identical performance
C
std::bind is always faster
D
Lambda has argument forwarding overhead
38

Question 38

What is lambda template argument deduction (C++20)?

cpp
auto lambda = []<typename T>(T value) {
    return value;
};

lambda(42);     // T = int
lambda("hello"); // T = const char*

// Equivalent to template lambda with auto
A
Explicit template syntax in lambda parameters allowing more control over type deduction than auto parameters
B
Automatic type deduction
C
No type deduction
D
Forced type deduction
39

Question 39

What is the difference between lambda and function pointer conversion?

cpp
auto lambda = [](int x) { return x * 2; };

using FuncPtr = int(*)(int);
FuncPtr ptr = lambda; // Error: lambda not convertible

// But stateless lambda can be:
auto stateless = +[](int x) { return x * 2; }; // Unary + converts
A
Lambdas with captures cannot convert to function pointers, stateless lambdas can be converted using unary + operator
B
All lambdas convert to function pointers
C
Lambdas with captures can convert
D
Stateless lambdas cannot convert
40

Question 40

What are the fundamental principles for effective lambda usage in C++?

A
Use lambdas for inline functions and algorithms, prefer value capture for safety, use mutable for state, consider std::function for storage, avoid captures that dangle, and use auto&& for perfect forwarding parameters
B
Never use lambdas in C++
C
Use lambdas for all functions
D
Avoid lambda captures

QUIZZES IN C++