wayne
wayne

Reputation: 11

lambda output in C++

The output of the following code is 0, 0. What is the problem with the code? m is passed by reference, it should be 1, right?

int main()
{
    int m = 0;
    int n = 0;
    [&, n]() {m = n + 1; };
    cout << m << endl << n << endl;
}

Upvotes: 0

Views: 69

Answers (1)

Praetorian
Praetorian

Reputation: 109149

You need to invoke the lambda

[&, n]() {m = n + 1; }();
//                    ^^

Now the output should be what you expect.


As Piotr's comment says, you can also initialize a variable to hold the lambda and invoke that

auto lambda = [&, n]() {m = n + 1; };
lambda();

Upvotes: 6

Related Questions