Tuesday 4 April 2017

C++ lambda expression (anonymous function)











I found this expression in C++ (one of the most exciting features of C++11):



int i = ([](int j) { return 5 + j; })(6);


Why I get the 11? Please explain this expression.


Answer



[](int j) { return 5 + j; } is a lambda that takes an int as an argument and calls it j. It adds 5 to this argument and returns it. The (6) after the expression invokes the lambda immediately, so you're adding 6 and 5 together.




It's roughly equivalent to this code:



int fn(int j) {
return 5 + j;
}

int i = fn(6);



Except, of course, that it does not create a named function. A smart compiler will probably inline the lambda and do constant folding, resulting in a simple reduction to int i = 11;.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...