C++ Interview Questions

22 Questions
C++ Programming

C++ Programming

Embedded SystemsIoTOther

Question 6

What is a lambda function in C++?

Answer:

A lambda function in C++ is an anonymous function that can be defined in-place and used to encapsulate a small piece of functionality. Introduced in C++11, lambda functions provide a concise way to define function objects and can capture variables from their surrounding scope. They are particularly useful for short, throwaway functions and are commonly used in algorithms and event handling.

Syntax of Lambda Functions:
The basic syntax of a lambda function in C++ is as follows:

[capture](parameters) -> return_type {
    // function body
};
  • Capture: The capture clause (inside square brackets []) specifies which variables from the surrounding scope are accessible inside the lambda function.
  • Parameters: The parameter list (inside parentheses ()) specifies the input parameters for the lambda function.
  • Return Type: The return type (optional, preceded by ->) specifies the return type of the lambda function. It can be omitted if the return type can be inferred.
  • Function Body: The function body (inside curly braces {}) contains the code to be executed.

Capture Modes:

  • [ ] captures nothing.
  • [&] captures all variables by reference.
  • [=] captures all variables by value.
  • [this] captures the this pointer by value.
  • [x, &y] captures x by value and y by reference.

Examples:

  1. Basic Lambda Function:

    #include <iostream>
    
    int main() {
        auto hello = []() {
            std::cout << "Hello, World!" << std::endl;
        };
        hello(); // Outputs: Hello, World!
        return 0;
    }
  2. Lambda with Parameters and Return Type:

    #include <iostream>
    
    int main() {
        auto add = [](int a, int b) -> int {
            return a + b;
        };
        std::cout << "Sum: " << add(3, 4) << std::endl; // Outputs: Sum: 7
        return 0;
    }
  3. Capturing Variables:

    #include <iostream>
    
    int main() {
        int x = 10;
        int y = 20;
    
        auto sum = [x, y]() {
            return x + y;
        };
    
        std::cout << "Sum: " << sum() << std::endl; // Outputs: Sum: 30
        return 0;
    }
  4. Capturing by Reference:

    #include <iostream>
    
    int main() {
        int x = 10;
        int y = 20;
    
        auto increment = [&x, &y]() {
            ++x;
            ++y;
        };
    
        increment();
        std::cout << "x: " << x << ", y: " << y << std::endl; // Outputs: x: 11, y: 21
        return 0;
    }
  5. Using Lambda Functions with Standard Algorithms:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
    
        std::for_each(numbers.begin(), numbers.end(), [](int n) {
            std::cout << n << " ";
        });
        // Outputs: 1 2 3 4 5
    
        std::cout << std::endl;
    
        std::transform(numbers.begin(), numbers.end(), numbers.begin(), [](int n) {
            return n * n;
        });
    
        std::for_each(numbers.begin(), numbers.end(), [](int n) {
            std::cout << n << " ";
        });
        // Outputs: 1 4 9 16 25
    
        return 0;
    }

Use Cases:

  1. Short Functions: Lambdas are ideal for short functions that are used only once or a few times.
  2. Event Handling: Lambda functions can be used as callbacks or event handlers.
  3. Standard Algorithms: Lambdas are often used with standard algorithms like std::for_each, std::transform, and std::sort for in-place functionality.
  4. Custom Comparators: Lambdas can be used to define custom comparators for sorting and searching operations.
  5. Encapsulation: Lambdas can encapsulate small units of work, making code more modular and easier to read.

Summary:
Lambda functions in C++ provide a powerful and flexible way to define anonymous functions inline. They simplify the code by eliminating the need for separate function declarations, and their ability to capture variables from the surrounding scope makes them extremely useful for concise and expressive code. Lambdas are widely used in modern C++ programming, particularly in conjunction with standard algorithms and event-driven programming.

Recent job openings