4

I am working in ESP8266 AsyncWebserver library and have been using this [](parameter) as an argument to some functions as shown below but does not really know what it means. Being a neophyte I am curious to know what does this convention means, its functionalities and how to use it. Hopefully experts here would help me with this.

server.on("/page",HTTP_GET,[](AsyncWebServerRequest * request){
    some code....;
    request->getParam("Param1")->value();
});

1 Answer 1

6

That is called a lambda expression and it's a way of including the content of a function as a parameter anonymously instead of writing an actual function and using the name of it.

It's shorthand for:

void myCallback(AsyncWebServerRequest * request) {
    // some code....;
    request->getParam("Param1")->value();
}

// ...

server.on("/page", HTTP_GET, myCallback);

It does have a few benefits over traditional functions at the expense of readability, such as the ability to "capture" local variables from the surrounding scope.

7
  • Thanks Mr.@Majenko, I will look further about this topic. So in the above example instead of creating a new function as a callback they used lambda function on the go to use locally within the function scope itself Am I right. Im just curious to know can we use the variables declared in server.on function inside the lambda
    – Mr.B
    Apr 27, 2020 at 10:19
  • 2
    All is explained in the link. But any variable that is defined within the function that server.on appears in can be "captured" by placing it between the [...], so you can then use it from within the lambda expression itself.
    – Majenko
    Apr 27, 2020 at 10:22
  • Thanks Mr.@Majenko thats useful
    – Mr.B
    Apr 27, 2020 at 11:17
  • 2
    More generally, the lambda is actually shorthand for a class declaration somewhere in the enclosing scope, struct unnamed_lambda_helper { /* captured local variables are data members of this class */ auto operator()(/* arguments here */) -> /* return type here, if specified */ { /* body here */ } };, and then the expression creates an instance of this class.
    – HTNW
    Apr 27, 2020 at 18:48
  • 1
    @PeterMortensen It is a C++11 feature (meaning older compilers may not support it). Of course, other languages do have their own version of this. To the best of my knowledge, C does not.
    – Cort Ammon
    Apr 28, 2020 at 0:45

Your Answer

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

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