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.

Community
  • 1
  • 1

1 Answers1

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;.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 1
    As a dabbler in C++, and current C# developer, what does the `[]` denote? Whenever I see brackets, I think array. – Major Productions Oct 07 '12 at 01:48
  • 5
    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. – cdhowie Oct 07 '12 at 01:53