0
0
CppConceptBeginner · 3 min read

What is Lambda Function in C++: Simple Explanation and Example

A lambda function in C++ is a small, unnamed function defined directly in the code where it is used. It allows you to write quick, inline functions without needing to create a separate named function.
⚙️

How It Works

A lambda function in C++ is like a mini-function you write right where you need it, without giving it a name. Imagine you want to quickly sort a list of numbers but with a special rule. Instead of writing a full function somewhere else, you write this small function directly inside your sorting code.

It works by using a special syntax with square brackets [] to capture variables from the surrounding code, parentheses () for parameters, and curly braces {} for the function body. This makes your code cleaner and easier to read, especially when the function is simple and used only once.

💻

Example

This example shows a lambda function that adds two numbers and prints the result.

cpp
#include <iostream>

int main() {
    // Define a lambda that takes two ints and returns their sum
    auto add = [](int a, int b) {
        return a + b;
    };

    int result = add(5, 3);
    std::cout << "Sum is: " << result << std::endl;
    return 0;
}
Output
Sum is: 8
🎯

When to Use

Use lambda functions when you need a quick, simple function for a short task, especially if you don't want to create a separate named function. They are great for passing small functions as arguments to other functions, like sorting or filtering data.

For example, if you want to sort a list of names by length or filter numbers that are even, lambda functions let you write that logic right where you use it, making your code shorter and easier to understand.

Key Points

  • Lambda functions are unnamed, inline functions defined with []() syntax.
  • They can capture variables from the surrounding scope to use inside.
  • They make code cleaner by avoiding separate function declarations for small tasks.
  • Commonly used with algorithms like sort, for_each, and transform.

Key Takeaways

Lambda functions are small, unnamed functions written inline in C++ code.
They use special syntax with square brackets to capture variables from outside.
Lambdas simplify code by avoiding separate function declarations for short tasks.
They are especially useful when passing functions as arguments to algorithms.
Use lambdas to write clearer and more concise code for quick operations.