All about lambda functions in C++(from C++11 to C++17)
Tags: cpp, tutorial, programming, computerscience
Published: 2019-11-16 13:23:30

<!-- wp:paragraph -->
<p>Lambda function is quite an intuitive concept of <a rel="noreferrer noopener" aria-label="Modern C++ (opens in a new tab)" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#1e0bed" class="color">Modern C++</span></a> introduced in C++11, So there are already tons of articles on lambda function tutorial over the internet. But still, there are some untold things(like IIFE, types of lambda, etc.) left, which nobody talks about. Therefore, here I am to not only show you lambda function in C++ but we'll also cover how it works internally &amp; other aspects of Lambda.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Title of this article is a bit misleading. Because <strong><em>lambda doesn't always synthesize to function pointer</em></strong>. It's an expression(precisely unique closure). But I have kept it that way for simplicity. So from now on, I will use lambda function &amp; expression interchangeably.</p>
<!-- /wp:paragraph -->


> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com).


<!-- wp:heading -->
<h2>What is lambda function?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A lambda function is short snippets of code that</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>not worth naming(unnamed, anonymous,  disposable, etc. Whatever you can call it),</li><li>and also not reused. </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>In other words, it's just syntactic sugar. lambda function syntax is defined as: </p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"cpp","linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[ capture list ] (parameters) -> return-type  
{   
    method definition
} </pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Usually, <strong><em>compiler evaluates a return type of a lambda function itself</em></strong>. So we don't need to specify a trailing return type explicitly i.e.  <code style="font-size: 16px;">-&gt; return-type</code>. </li><li>But in some complex cases, the compiler unable to deduce the return type and we need to specify that.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Why we should use a lambda function?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>C++ includes many useful generic functions like <code>std::for_each</code>, which can be handy. Unfortunately, they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. Consider the following code for an example: </p>
<!-- /wp:paragraph -->


```c++
struct print
{
    void operator()(int element)
    {
        cout << element << endl;
    }
};
int main(void)
{
    std::vector<int> v = {1, 2, 3, 4, 5};
    std::for_each(v.begin(), v.end(), print());
    return 0;
}
```

<!-- wp:list -->
<ul><li>If you  use&nbsp;<code>print</code>&nbsp;once, in that specific place, it seems overkill to be writing a whole class just to do something trivial and one-off. </li><li>However, for this kind of situation inline code would be more suitable &amp; appropriate which can be achieved by lambda function as follows: </li></ul>
<!-- /wp:list -->

```c++
std::for_each(v.begin(), v.end(), [](int element) { cout << element << endl; });
```

<!-- wp:heading -->
<h2>How lambda functions works internally?  </h2>
<!-- /wp:heading -->

```c++
[&i] ( ) { std::cout << i; }
// is equivalent to
struct anonymous
{
    int &m_i;
    anonymous(int &i) : m_i(i) {}
    inline auto operator()() const
    {
        std::cout << i;
    }
};
```

<!-- wp:list -->
<ul><li>The <strong><em>compiler generates unique closure as above for each lambda function</em></strong>.  Finally, the secret revealed.</li><li>Capture list will become a constructor argument in closure, If you capture argument as value then corresponding type data member is created within the closure.</li><li> Moreover, you can  declare variable/object in the lambda function argument, which will become an argument to call operator i.e. <code>operator()</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits of using a lambda function</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Zero cost abstraction. Yes! you read it right. <strong><em>lambda doesn't cost you performance &amp; as fast as a normal function</em></strong>. </li><li> In addition, code becomes compact, structured &amp; expressive.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Learning lambda expression</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Capture by reference/value</h3>
<!-- /wp:heading -->

```c++
int main()
{
    int x = 100, y = 200;
    auto print = [&] { // Capturing object by reference
        std::cout << __PRETTY_FUNCTION__ << " : " << x << " , " << y << std::endl;
    };
    print();
    return 0;
}
```

<!-- wp:paragraph -->
<p>Output:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"cpp","linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">main()::&lt;lambda()> : 100 , 200</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>In the above example, I have mentioned <code>&amp;</code> in capture list. which captures variable <code>x</code> &amp; <code>y</code> as reference. Similarly,  <code>=</code> denotes captured by value, which will create data member of the same type within the closure and copy assignment will take place. </li><li>Note that, the parameter list is optional,<strong><em> you can omit the empty parentheses if you do not pass arguments</em></strong> to the lambda expression.  </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Lambda capture list </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The following table shows different use cases for the same: </li></ul>
<!-- /wp:list -->

<!-- wp:table {"className":"is-style-stripes"} -->
<figure class="wp-block-table is-style-stripes"><table class=""><tbody><tr><td>[ ] ( ) { }</td><td>no captures</td></tr><tr><td>[=] ( ) { }</td><td>captures everything by copy(not recommendded)</td></tr><tr><td>[&amp;] ( ) { }</td><td>captures everything by reference(not recommendded)</td></tr><tr><td>[x] ( ) { }</td><td>captures x by copy</td></tr><tr><td>[&amp;x] ( ) { }</td><td>captures x by reference</td></tr><tr><td>[&amp;, x] ( ) { }</td><td>captures x by copy, everything else by reference</td></tr><tr><td>[=, &amp;x] ( ) { }</td><td>captures x by reference, everything else by copy</td></tr></tbody></table></figure>
<!-- /wp:table -->

<!-- wp:heading {"level":3} -->
<h3 id="lambda-as-parameter">Passing lambda as parameter</h3>
<!-- /wp:heading -->

```c++
template <typename Functor>
void f(Functor functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
} 
*/
int g() { static int i = 0; return i++; }
int main()
{
    auto lambda_func = [i = 0]() mutable { return i++; };
    f(lambda_func); // Pass lambda
    f(g);           // Pass function
}
```

<!-- wp:paragraph -->
<p>Output: </p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Function Type : void f(Functor) [with Functor = main()::&lt;lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>You can also pass lambda function as an argument to other function just like a normal function which I have coded above.</li><li>If you noticed, here I have declared variable <code>i</code> in capture list which will become data member. As a result, every time you call <code>lambda_func</code>, it will be returned and incremented.  </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Capture member variable in lambda or this pointer </h3>
<!-- /wp:heading -->

```c++
class Example
{
public:
    Example() : m_var(10) {}
    void func()
    {
        [=]() { std::cout << m_var << std::endl; }(); // IIFE
    }
private:
    int m_var;
};
int main()
{
    Example e;
    e.func();
}
```

<!-- wp:list -->
<ul><li><em><code>this</code></em> pointer can also be captured using <code>[this]</code>, <code>[=]</code> or <code>[&amp;]</code>. In any of these cases, class data members(including <em>private</em>) can be accessed as you do in a normal method. </li><li>If you see the lambda expression line, I have used extra <code>()</code> at the end of the lambda function declaration which used to calls it right thereafter declaration. It is called  <a rel="noreferrer noopener" aria-label="IIFE (opens in a new tab)" href="https://stackoverflow.com/questions/44868369/how-to-immediately-invoke-a-c-lambda" target="_blank"><span style="color:#1927e7" class="color">IIFE</span></a> (<strong><em>Immediately Invoked Function Expression</em></strong>).</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>C++ lambda function types</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Generic lambda</h3>
<!-- /wp:heading -->

```c++
const auto l = [](auto a, auto b, auto c) {};
// is equivalent to
struct anonymous
{
    template <class T0, class T1, class T2>
    auto operator()(T0 a, T1 b, T2 c) const
    {
    }
};
```

<!-- wp:list -->
<ul><li>Generic lambda introduced in C++14 which can captures parameters with <code>auto</code> specifier. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Variadic generic lambda </h3>
<!-- /wp:heading -->

```c++
void print() {}
template <typename First, typename... Rest>
void print(const First &first, Rest &&... args)
{
    std::cout << first << std::endl;
    print(args...);
}
int main()
{
    auto variadic_generic_lambda = [](auto... param) {
        print(param...);
    };
    variadic_generic_lambda(1, "lol", 1.1);
}
```

<!-- wp:list -->
<ul><li>Lambda with variable parameter pack will be useful in many scenarios like debugging, repeated operation with different data input, etc.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>mutable lambda function</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Typically, a lambda's function call operator is const-by-value which means <strong><em>lambda requires <code>mutable</code>&nbsp; keyword if you are capturing anything by-value</em></strong>.</li></ul>
<!-- /wp:list -->

```c++
[]() mutable {}
// is equivalent to
struct anonymous
{
    auto operator()()  // call operator
    {
    }
};
```

<!-- wp:list -->
<ul><li>We have already seen an example of this above.  I hope you <a href="#lambda-as-parameter"><span style="color:#0b26d2" class="color">noticed</span></a> it.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Lambda as a function pointer </h3>
<!-- /wp:heading -->

```c++
#include <iostream>
#include <type_traits>
int main()
{
    auto funcPtr = +[] {};
    static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
```

<!-- wp:list -->
<ul><li>You can force the compiler to generate lambda as a function pointer rather than closure by adding <code>+</code> infront of it as above. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Higher-order returning lambda functions </h3>
<!-- /wp:heading -->

```c++
const auto less_than = [](auto x) {
    return [x](auto y) {
        return y < x;
    };
};
int main(void)
{
    auto less_than_five = less_than(5);
    std::cout << less_than_five(3) << std::endl;
    std::cout << less_than_five(10) << std::endl;
    return 0;
}
```

<!-- wp:list -->
<ul><li>Going a bit further, lambda function can also return another lambda function. This will open the doors of endless possibility for customization, code expressiveness &amp; compactibility(BTW, there is no word like this) of code.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>constexpr lambda expression</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Since C++17, a lambda expression can be declared as&nbsp;<a href="http://www.vishalchovatiya.com/when-to-use-const-vs-constexpr-in-cpp/" target="_blank" rel="noreferrer noopener" aria-label="constexpr (opens in a new tab)"><span style="color:#2614e9" class="color">constexpr</span></a>.</p>
<!-- /wp:paragraph -->

```c++
constexpr auto sum = [](const auto &a, const auto &b) { return a + b; };
/*
    is equivalent to
    constexpr struct anonymous
    {
        template <class T1, class T2>
        constexpr auto operator()(T1 a, T2 b) const
        {
            return a + b;
        }
    };
*/
constexpr int answer = sum(10, 10);
```

<!-- wp:list -->
<ul><li>Even if you don't specify&nbsp;<code>constexpr</code>&nbsp;, the function call operator will be &nbsp;<code>constexpr</code>&nbsp;anyway, if it happens to satisfy all <a rel="noreferrer noopener" aria-label="constexpr function requirements (opens in a new tab)" href="https://en.cppreference.com/w/cpp/language/constexpr" target="_blank"><span style="color:#370aec" class="color">constexpr function requirements</span></a></li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Closing words</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I hope you enjoyed this article. I have tried to cover most of the intricacies around lambda with a couple of simple &amp; small examples. You should use lambda wherever it strikes in your mind considering code expressiveness &amp; easy maintainability like you can use it in custom deleters for smart pointers &amp; with most of the STL algorithms.</p>
<!-- /wp:paragraph -->


## You may like these also

- [21 new features of Modern C++ to use in your project](https://dev.to/visheshpatel/21-new-features-of-modern-c-to-use-in-your-project-3f87)
- [C++ type casting with example for C developers](https://dev.to/visheshpatel/c-type-casting-with-example-for-c-developers-29b8)
- [7 best practices for exception handling in C++](http://www.vishalchovatiya.com/7-best-practices-for-exception-handling-in-cpp-with-example/)

[Have any suggestions, query or wants to say `Hi`? Take the Pressure Off, you are just a click away.](http://www.vishalchovatiya.com/contact-2/)🖱️