C++ Structure of a Lambda Expression

w‮gi.ww‬iftidea.com

A lambda expression in C++ has the following structure:

[capture list] (parameter list) -> return type { function body }
  • The capture list is an optional list of variables from the enclosing scope that the lambda function can use. It is specified within square brackets [].
  • The parameter list is a comma-separated list of parameters that the lambda function takes, similar to a regular function parameter list. It is specified within parentheses ().
  • The -> arrow is used to specify the return type of the lambda function, which is also optional. If the lambda function doesn't have a return type, you can omit this part.
  • The function body is the code that the lambda function executes, specified within curly braces {}. It can contain any valid C++ code, including control structures, function calls, and variable declarations.

Here's an example of a lambda expression that takes two integer parameters and returns their sum:

[](int a, int b) -> int { return a + b; }

This lambda expression doesn't capture any variables from the enclosing scope and has an explicit return type of int. It takes two integer parameters a and b and returns their sum using the + operator.