Intro Lambda Expressions
Part of the Logic & Flow section of Coddy's C++ journey — lesson 42 of 56.
Lambda expressions are a powerful C++ feature that allows you to create small, anonymous functions right where you need them. Think of them as mini-functions that you can define and use without having to write a separate function declaration.
The basic syntax for a lambda expression follows this pattern: [](){}. The square brackets [] are called the capture clause, the parentheses () hold parameters (just like regular functions), and the curly braces {} contain the function body.
The capture clause controls which variables from the surrounding scope the lambda can use. The most common forms are:
[=] — capture all local variables by value (the lambda gets its own copy)[&] — capture all local variables by reference (the lambda accesses the originals)[] — capture nothing (the lambda cannot use any outside variables)Here's how to create and call a simple lambda:
auto myLambda = []() {
std::cout << "Hello from Lambda!" << std::endl;
};
myLambda(); // Call the lambda functionYou can also define and execute a lambda immediately without storing it in a variable:
[]() {
std::cout << "Immediate execution!" << std::endl;
}();Lambda expressions are particularly useful for short, one-time functions that you don't want to define separately. They make your code more concise and keep related logic close together.
Challenge
EasyCreate a program that demonstrates the basic syntax and execution of lambda expressions. This challenge will test your understanding of how to define and call simple lambda functions without parameters.
Your program should:
- Create a lambda expression that prints
Hello from Lambda! - Store this lambda in a variable using the
autokeyword - Call the lambda function to execute it
- Create a second lambda expression that prints
Lambda executed successfully! - Execute this second lambda immediately without storing it in a variable
Use the following exact output format:
Hello from Lambda!
Lambda executed successfully!Remember that lambda expressions use the syntax [](){} where the square brackets [] are the capture clause, the parentheses () hold parameters (empty for this challenge), and the curly braces {} contain the function body. You can store a lambda in a variable using auto variableName = [](){...}; and then call it with variableName();. For immediate execution, you can use the syntax [](){...}(); which defines and calls the lambda in one statement.
Cheat sheet
Lambda expressions are anonymous functions that can be defined inline. They use the syntax [](){} where:
[]- capture clause (controls access to outer variables)()- parameters{}- function body
Common capture clause forms:
[]- capture nothing[=]- capture all outer variables by value[&]- capture all outer variables by reference
Store and call a lambda:
auto myLambda = []() {
std::cout << "Hello from Lambda!" << std::endl;
};
myLambda(); // Call the lambda functionExecute a lambda immediately:
[]() {
std::cout << "Immediate execution!" << std::endl;
}();Try it yourself
#include <iostream>
using namespace std;
int main() {
// TODO: Write your code below
// Create a lambda expression that prints "Hello from Lambda!"
// Store it in a variable using auto keyword
// Call the lambda function
// Create a second lambda that prints "Lambda executed successfully!"
// Execute it immediately without storing in a variable
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency7Advanced Functions
Pass by ReferenceIntro Lambda ExpressionsLambdas with ParametersLambdas with Return ValuesIntroduction to RecursionRecursive FactorialLambda Sort2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items