-1

#include<bits/stdc++.h>
using namespace std;


auto fnc = [&]()->void{

    cout << "HELLO WORLD";
    return;
};


int main()
{

    fnc();


    return 0;
}

ERROR OCURRED WHILE BUILDING THIS C++ CODE: non-local lambda expression cannot have a capture-default

But when i remove the ampersand from capture list the code is running pretty fine.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    Does this answer your question? [Non local lambda and capturing variables - what does "block scope" means](https://stackoverflow.com/questions/19344955/non-local-lambda-and-capturing-variables-what-does-block-scope-means) – 0x0000dead Sep 16 '21 at 19:07
  • Please read [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Sep 16 '21 at 20:45

1 Answers1

0

Not sure if I'm right, but & makes that the variables of the scope will have access to the lambda by reference, and since there are no parameters you are passing to the lambda function, it throws an error.

[] means that the variables you are refering to will have no access, so maybe that's the reason your code is running ok when you delete & from the capture list

https://learn.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=msvc-160

UPDATE:

auto lambda = [&]() -> void{
    cout << "Hola mundo";
};

int main()
{
    lambda();
    return 0;
}`
  • I dont think so it will make any difference.But while i compile above code with default capture with gcc version 6 or below it works pretty fine – VASU OBEROI Sep 17 '21 at 04:46
  • Okay, have you tried removing the `return` keyword? If if is a `void` function then it shouldn't return something. EDIT: This is the code I wrote, it is literally the same as yours but without the `return` keyword. (I updated the answer) –  Sep 17 '21 at 04:56
  • Also, why are you including `bits/stdc++.h` –  Sep 17 '21 at 05:00