Uttam Malakar
Uttam Malakar

Reputation: 714

What is the use of lambda functions?

Can anyone help me understand the following code

#include <iostream>
using namespace std;

int main()
{
    auto hello = []() -> void {
        cout << "Hello World";
    };

    // Call the lambda function
    hello();
}

What is the use of auto hello = []() -> void here? I don't understand the meaning of the terminating semicolon after the curly brace (line 7)

Upvotes: 2

Views: 178

Answers (1)

us2012
us2012

Reputation: 16263

Read it as if it were one line:

auto hello = []() -> void { cout << "Hello World"; };

hello is a variable which holds a lambda that

  • doesn't capture external variables ([]),
  • does not take parameters (()),
  • returns void (-> void, this is called 'trailing return type', specifying the return type of the lambda just like you would for an ordinary function. This is actually unnecessary here.), and
  • consists of the single cout statement within its body.

It isn't actually executed until the next line, where it is explicitly called.

Upvotes: 7

Related Questions