DEV Community

Cover image for Lambda functions in C++
Satyam Lachhwani
Satyam Lachhwani

Posted on

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

Top comments (1)

Collapse
 
arjunjv profile image
sai kiran jv

cool stuff !!