5
#include <iostream>

using namespace std;

int main()
{

    static bool temp([]{ 
        cout <<"Hi ";
        return false;});


   cout <<"temp "<< temp;

   return 0;
}

It does not execute lambda. But if we declare lambda separately like:

#include <iostream>

using namespace std;

int main()
{
    auto lambda = []{ 
        cout <<"Hi ";
        return false;};

    static bool temp(lambda());


   cout <<"temp "<< temp;

   return 0;
}

It will execute it. What am I missing here?

2
  • 3
    You're not calling it in the first example. Commented Dec 18, 2019 at 1:16
  • 1
    Try changing [] to [=] and see what happens. Commented Dec 18, 2019 at 1:37

1 Answer 1

12

You need to invoke the lambda, just as the 2nd code snippet does.

static bool temp([]{ 
    cout <<"Hi ";
    return false;}());
//                ^^

LIVE


PS: In the 1st code snippet temp will always be initialized as true, because lambda without capture list could convert to function pointer implicitly; which is a non-null pointer and then could convert to bool with value true.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.