RudolphRedNose
RudolphRedNose

Reputation: 121

C++ Beginner Lambda's

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

Answers (3)

P0W
P0W

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

Pierre Fourgeaud
Pierre Fourgeaud

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

us2012
us2012

Reputation: 16253

You have defined a lambda, but you never run it. Try

auto mylambda = [&j](){...}; 
mylambda();

Upvotes: 4

Related Questions