Lambda functions in C++

satyam1203

Satyam Lachhwani

Posted on March 3, 2021

Lambda functions in C++

Hi people,

Similar to other languages, C++ also has lambda expressions. The official documentation defines it as:

Lambda expression constructs a closure: an unnamed function object capable of capturing variables in scope.

Let's first see it in action before going into details:

int a = 4;
auto isEven = [](int a) { return a%2 == 0; };
cout<<isEven(a);
// prints 1 - means the number is even
Enter fullscreen mode Exit fullscreen mode

Cool. Isn't it? 😉

In C++, the lambda function has its own complexities. Lambda expressions are useful when a one-liner function is required to be passed to some other function. E.g, transform, copy, remove, etc. I'll try to cover them in upcoming articles.
 

Structure of a lambda function:

👉 [ ] contains the variables that the lambda function captures from the current scope. (By default, Lambda function can't use variables from the current scope, for each variable that is used inside the lambda function body we add it inside [ ] separating them by comma. There are some exceptions to it which you can see by referring to the official documentation)

👉 ( ) contains the function parameters with their type that the lambda function accepts.

👉 { } contains function body. In most cases, it only has a return statement.

Another example:

int num1 = 5;
auto add_with_param = [num1] (int num2) {return num1 + num2;};
cout<<add_with_param(12);
// returns 17
Enter fullscreen mode Exit fullscreen mode

 

Lambda Capture ways:

📍 [&] : Captures all variables from outer scope by reference.

📍 [=] : Captures all variables from outer scope by value.

📍 [&var] : Capture a particular variable var by reference.

📍 [var] : Capture a particular variable var by value.

📍 [var1, &var2] : Mixed Capture of different variables in different ways.
 

Other important points:

  • If the Lambda function doesn't accept any parameter, ( ) section may be skipped.
int b = 5;
auto isEven = [b] {return b % 2 == 0;};
cout<<isEven();
// returns 0 - means the number is not even
Enter fullscreen mode Exit fullscreen mode
  • Any variable or object captured by the Lambda function(by value) can not be mutated inside the Lambda function.

  • After ( ) section in the structure of the Lambda function, its return type may be specified (Optional). If omitted, the return type is implied by the function return statement or void if it doesn't return anything.

  • Lambda functions can work only on C++ 11 and above.

For full reference and more examples, visit here

If you find anything wrong or if you know some more exciting functions or other stuff related to C++, please drop a comment below so we learn together.

My Profile -

Github
LinkedIn

💖 💪 🙅 🚩
satyam1203
Satyam Lachhwani

Posted on March 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related