6

I am learning C++14 lambdas with const, and today my friend showed me the following. I could not understand it.

  1. Is it a lambda function? The syntax does not matches what I see usually.

  2. it syntax matches with a lambda function, but it fails with a long error.

int main()
{
    // 1.
    const auto x = [&]{
        auto l = 0;
        l = 99;
        return l;
    }();

    std::cout << x << endl;

    // 2.    
    const auto y = [&](){
        auto l = 0;
        l = 99;
        return l;
    };

    std::cout << y << endl;   

    return 0;
}

I want to know what 1 is, and why 2 fails to compile.

1 Answer 1

16

I wanted to know what is 1. and why 2. fails to compile.

(1)

const auto x = [&]{
        auto const_val = 0;
        const_val = 99;
        return const_val;
    }();
// ..^^  <--- execution

This is the definition and execution of a lambda that doesn't receive arguments (so the () part after [&] is optional and, in this case, omitted).

So x is an int (a const int) initialized with 99 (the value returned by the lambda)

As you can see, the name const_val for the integer variable inside the lambda is a fake, because the variable is intialized with 0 and then modified assigning to it the value 99.

(2)

const auto y = [&](){
auto l = 0;
l = 99;
return l;
};

This is the definition only (no execution) of a lambda that receive no arguments.

So y is a variable (well, a constant) that contain the lambda and when you write

std::cout << y << endl; 

you get an error because isn't defined the output for a lambda; you should try with

std::cout << y() << endl;

to execute the lambda and print the returned value (again 99).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.