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
#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.