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.

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,

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,

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,

How to pass outer scope elements inside lambda functions,

Case 1: Using [=]

Case 2: Using [&]

Checkout this example this clearly shows how to use outer scope elements inside the lambda functions.

Thanks.