Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple lambda function I could not understand

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.

like image 626
Roshan Mehta Avatar asked Dec 03 '18 23:12

Roshan Mehta


People also ask

How do you explain Lambda?

Lambda is a compute service that lets you run code without provisioning or managing servers.

What is Lambda for beginners?

AWS Lambda is a service which computes the code without any server. It is said to be serverless compute. The code is executed based on the response of events in AWS services such as adding/removing files in S3 bucket, updating Amazon DynamoDB tables, HTTP request from Amazon API Gateway etc.

How lambda function is different from normal function?

The lambda functions defined above are like single-line functions. These functions do not have parenthesis like the def defined functions but instead, take parameters after the lambda keyword as shown above. There is no return keyword defined explicitly because the lambda function does return an object by default.


1 Answers

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

like image 78
max66 Avatar answered Sep 18 '22 22:09

max66