Nesting Lambda Expressions

Hi,

Will you, please, explain how the outcome here is 13, exactly:

1
2
int i = [](int x) { return [](int y) { return y * 2; }(x)+3; }(5);
cout << "i = " << i << endl;

It seems that you essentially have
1
2
int i = foo(5);
cout << "i = " << i << endl;

where
auto foo = [](int x) { return bar(x) + 3; };

Interesting. On one hand you have nested expressions.
On the other you call a function in the same statement where you define that function.
first thing
ADVICE: Avoid such nested expressions as they are ugly and error prone

This is what happens:
1) call the first function with parameter x = 5
2) return value would be --> [](int y){ return y * 2; }(5) + 3
3) call the second function with parameter 5 and add 3 to the return value
4) i = 5 * 2 + 3 = 13
5) done :)

it's exactly the same as the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int g(int y)
{
    return y * 2;
}

int f(int x)
{
    return g(x) + 3;
}

int main()
{
    int i = f(5);
    cout << "i = " << i << endl;
}
Last edited on
Got it!
Thank you very much, guys. :)
Topic archived. No new replies allowed.