Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a lambda immediately?

Tags:

c++

c++11

lambda

How can I run a lambda immediately instead of storing it and then run it?

Instead of storing the lambda like this:

auto lambda = [&](){ std::cout << ++x << '\n'; }

I am trying to run it immediately like this:

[&](){ std::cout << ++x << '\n'; }

But that gives me this error message:

Warning: expression result unused
like image 935
Jens273 Avatar asked May 14 '16 03:05

Jens273


1 Answers

You can invoke the lambda immediately by placing parenthesis at the end like shown below:

int x = 0;
[&]{ std::cout << ++x << '\n'; }();
                             // ^^

Now this will print out 1

like image 64
Andreas DM Avatar answered Sep 25 '22 21:09

Andreas DM