Lambda expressions
Lambda expression, more often just called "lambdas", are a convenient way to write a snippet of code in a form of an object, so that it can be sent as a function argument and reused later. Lambdas are mostly used for:
- creating named objects inside functions, that can be later reused just like functions, without polutting the global namespace.
- creating "anonymous" snippets of code that can be sent to other functions (e.g. standard library algorithms).
We recommend to look at Simple examples and Practical usage for some examples.
Lambdas are often called anonymous functions, functors or function objects.
None of these names are correct, although can be used when talking about lambdas.
Indeed, lambdas create an invisible object, although they are only expressions themselves.
Because of the way lambdas work (creating a magic, invisible object, of some magic, not-known type), to assign them to an object,
we need to use the keyword auto
, or make use of the standard library type - std::function
(we will learn about it further in the course).
The syntax
A lambda must have a body, in which we will write our code and a capture list (that can be empty). The parameter list is optional, although very often used. We can add various other things to the lambda expression, like attributes, explicit return type, etc., although they are neither mandatory nor often used, so we will talk about them further in the course.
Capture list
As we know from the lesson about functions, local variables (e.g. from the main
function) are not known in the body of any other function.
The same thing applies to the lambda expressions. Local variables from a function are not visible inside a lambda expression,
that's why they need to be captured in the capture list.
int five = 5;
auto get7 = [five] () { return five + 2; };
std::cout << get7();
7
In case of a lambda expression with an empty parameter list, the parentheses can be ommited.
int five = 5;
auto get7 = [five] { return five + 2; };
std::cout << get7();
The variables captured in the capture list cannot be changed for now. There's a way to do that, but we will talk about it in the second course lesson.
Parameter list
The parameter list in the lambda expression works just like the one we know from functions. It allows us to declare with what parameters our lambda should be called, and then pass arguments to it.
auto multplyBy7 = [] (int a) { return a * 7; }; // a lambda with a parameter of type int
std::cout << multplyBy7(5); // the lambda called with an argument 5
35