problem about lambda.

I am learning Lambda expression, why the output is still 7.
It seems the lambda hasn't change the value.

1
2
3
4
int x=7;
[&x](){x=5;};
cout << x;
cin.get();


My implementation is vs2010. Could it be the vs2010 doesn't support c++11 quite well?
Last edited on
You haven't called the lambda, only defined it. You can either put the lambda in a variable and call it from there
1
2
auto Lamb = [&x](){x=5;};
Lamb();

or call the lambda in place [&x](){x=5;}(); (note the extra parentheses "()" call the lambda)
Last edited on
lays wrote:
Could it be the vs2010 doesn't support c++11 quite well?

Yes. You should upgrade to Visual Studio 2013.
http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx

Edit: you are defining the lambda function but you are not using it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    int x = 7;

    auto my_lambda = [&x]()
    {
        x = 5;
    };

    my_lambda();
    std::cout << x;
    std::cin.get();
}
5
Last edited on
thx alot.
Topic archived. No new replies allowed.