Cpp - Function Lambda Expressions

Introduction

A lambda expressions create inline anonymous functions.

Here's an example:

auto my_lambda = [](){ std::cout << "this is a test!" << std::endl; }; 
my_lambda(); 

This code produces the following output:

this is a test! 

The anonymous function executes the code between the { and } braces.

There's a semi-colon at the end of the line following the } brace.

The function is stored in the variable my_lambda and run using the same syntax as calling a function.

The lambda expression can have one or more arguments, which are specified within the parenthesis marks after the [ ] square brackets.

This example has two arguments:

auto multiply = [](int x, int y){ std::cout << "Total: " << x * y << std::endl; }; 
multiply(5, 5); 

Here's the output:

Total: 25

When a lambda expression has no arguments, the parentheses can be left out of the expression.

The first example didn't have parameters, so the following code removed the parentheses:

auto my_lambda = []{ std::cout << "this is a test!" << std::endl; }; 

The expression can return a value by specifying its return type (or auto) after a -> operator.

Here's a rewrite of the previous example that returns the sum of multiplying x and y.

auto multiply = [](int x, int y) -> int { return x * y; }; 
int sum = multiply(7, 17); 
std::cout << "Total: " << sum << std::endl; 

A lambda expression normally does not have access to the outside variables.

To reference the outside variables use [ ] square brackets, which are called the capture block.

List the variables inside the [ and ] brackets separated by commas.

int x = 7; 
auto multiply = [x](int y) -> int { return x * y; }; 
int sum = multiply(17); 
std::cout << "Total: " << sum << std::endl;