2

Possible Duplicate:
What is a lambda expression in C++11?

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.

0

1 Answer 1

14

[](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;.

Sign up to request clarification or add additional context in comments.

2 Comments

As a dabbler in C++, and current C# developer, what does the [] denote? Whenever I see brackets, I think array.
Unlike C#, C++ does not capture variables in the outer scope automatically. The [] contains a list of variables in the outer scope that you want to capture into the inner scope. You can capture things by value or by reference. (When capturing by reference, things are captured using C++ references; the lifetime of function locals is not extended in C++ like it is in C#.) In this particular case, the lambda is not capturing anything from the outer scope.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.