Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fix "lambda has no capture-default"

I’m using lambdas for the first time and having a problem which I can’t figure out.

I’m getting multiple errors

<source>: In lambda function:
<source>:7:19: error: 'x' is not captured
    7 |         int sum = x + y;
      |                   ^
<source>:6:20: note: the lambda has no capture-default
    6 |     auto lambda = []() {
      |                    ^
<source>:4:9: note: 'int x' declared here
    4 |     int x = 5, y = 10;
      |         ^
<source>:7:23: error: 'y' is not captured
    7 |         int sum = x + y;
      |                       ^
<source>:6:20: note: the lambda has no capture-default
    6 |     auto lambda = []() {
      |                    ^
<source>:4:16: note: 'int y' declared here
    4 |     int x = 5, y = 10;
      | 

My code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

int main() {
    int x = 5, y = 10;

    auto lambda = []() {
        int sum = x + y;
        std::cout << "Sum of x and y is: " << sum << std::endl;
    };

    lambda();
}

It says my variables are decleared but why are they not found?

>Solution :

The variables are not in the scope of the lambda because they are not captured or pass as arguments as seen in the error:

<source>:6:20: note: the lambda has no capture-default
    6 |     auto lambda = []() {
      | 

You could either capture the variables (there are multiple possibilities to do this -> see the references below)

auto lambda = [&]() {
...
};

or pass them as arguments

auto lambda = [](auto x, auto y) {
...
};

I would recommend reading "What does the word capture mean in the context of lambdas?", cppreference.com – Lambda expressions or Lambda expressions in C++ – Capture clause for more information about the different approaches.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading