Lambda Behavior
Hi All ,
I am trying to learn Lambda in CPP.
With the following code I am expecting an output
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
int main()
{
[]() {
cout <<"Hello World!\n";
};
return 0;
}
|
but I am a getting blank screen.
I tried running the above code in visual studio (16.4.2) and also online at online gdb.com .On both occasions no result.
My debugger says :
The breakpoint will not currently be hit .No executable code of the debugger's target code is associated with this line .
|
Can anyone suggest ,why it is getting skipped?
Regards
Last edited on
You define a lamda, but never actually execute the code.
As KBW says, you define a lambda, but you don't call it.
Your question is analogous to this:
Why isn't the function being called?
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
using namespace std;
void function()
{
cout << "Hello World!\n";
}
int main()
{
return 0;
}
|
|
You can call an anonymous lambda immediately after defining it:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
int main()
{
[]() {
cout <<"Hello World!\n";
}(); // NOTE ()
return 0;
}
|
or you can give it a name and call it when you like:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main()
{
auto lambda = []() {
cout <<"Hello World!\n";
};
cout << "Now call:";
lambda();
return 0;
}
|
Thx All ,
My bad , I forgot that end of the day its a function and needs to be called .
Topic archived. No new replies allowed.