C++11 Lambda Function : Example & Tutorial

In this article we will discuss, what is a C++11 Lambda Functions,  how to use Lambda Functions as Callbacks.

What is a Lambda Function?

Lambda functions are a kind of anonymous functions in C++. These are mainly used as callbacks in C++. Lambda function is like a normal function i.e.

  • You can pass arguments to it
  • It can return the result

But it doesn’t have any name. Its mainly used when we have to create very small functions to pass as a callback to an another API.

Before going deep into lambda functions, lets understand what was the need of lambda functions.

Advertisements

Need of Lambda functions

I have an array of int and I want to traverse on this array and print all ints using STL algorithm std::for_each.

Let’s do that using a function pointer,

#include <iostream>
#include <algorithm>

void display(int a)
{
    std::cout<<a<<" ";
}
int main() {
    int arr[] = { 1, 2, 3, 4, 5 };

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), &display);

    std::cout << std::endl;

}

In this above example, to do a simple display we created a separate function. Is there any way through which we can achieve our requirement and also avoid this overhead.

Rise of Lambda functions

To resolve this, use we can use lambda functions. A lambda function is a kind of anonymous function which doesn’t have any name but you can pass arguments and return results from it. Also all its content will work as in-line code.

Lambda function example is as follows,

[](int x) {
        std::cout<<x<<" ";
    }

Here,

  • [] is used to pass the outer scope elements
  • (int x) shows argument x is passed

 

Let’s see the above example with lambda functions,

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) {
            std::cout<<x<<" ";
        });

    std::cout << std::endl;

}

How to pass outer scope elements inside lambda functions

Case 1: Using [=]

    [=](int &x) {
        // All outer scope elements has been passed by value
    }

Case 2: Using [&]

    [&](int &x) {
        // All outer scope elements has been passed by reference
    }

Checkout this example this clearly shows how to use outer scope elements inside the lambda functions.
#include <iostream>
#include <algorithm>

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };

    int mul = 5;

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x) {
        std::cout<<x<<" ";
        // Can modify the mul inside this lambda function because
        // all outer scope elements has write access here.
            mul = 3;
        });
    std::cout << std::endl;

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [=](int &x) {
        x= x*mul;
        // Can not modify the mul inside this lambda function because
        // all outer scope elements has read only access here.
        // mul = 9;

        });
    std::cout << std::endl;

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) {

        // No access to mul inside this lambda function because
        // all outer scope elements are not visible here.
        //std::cout<<mul<<" ";
        });
    std::cout << std::endl;

}


Thanks.

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

7 thoughts on “C++11 Lambda Function : Example & Tutorial”

  1. Excellent tutorial, no words to say. Thank you so much for writing this article with such ease. I was struggling to understand lambda functions before going through this Article.Thank you sooooooooo much, you made by job very easy

  2. Simple amazing!

    I’ve been struggling to learn Lambda, watched videos on YouTube / read articles but nothing seemed to make sense. Then I came across this site and baam! everything was crystal clear.

    Thank you so much taking out the time do the tutorials!

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top