Reputation: 121
I'm a beginner that's just learning about lambdas and so I just want to make a lambda that captures a local variable from the outside function and is supposed to print its value and decrement it until it reaches 0. It compiles but doesn't display anything. Why?
void dummyFn(int &num)
{
int j = num;
[&j](){
while (j != 0)
{
cout << j << endl;
--j;
}
};
}
Upvotes: 1
Views: 120
Reputation: 47794
"It compiles but doesn't display anything."
You need to call it using ()
void dummyFn(int& num)
{
int j = num;
[&j](){
while (j != 0)
{
cout << j << endl;
--j;
}
} (); // Call the function !
}
Upvotes: 2
Reputation: 14510
Your lambda is defined, but now you have to run it:
auto fn = [&j](){ ... }; // definition
fn(); // Run
Or even:
[&j](){ ... } ();
// ^^^
Both examples are running the function.
Upvotes: 0
Reputation: 16253
You have defined a lambda, but you never run it. Try
auto mylambda = [&j](){...};
mylambda();
Upvotes: 4