Info

This post introduces C++ lambda expressions using a minimal example.
The goal is to understand what a lambda is and why you might use one, not to cover every advanced feature.

Error

This article is a WIP.

Introduction

In C++, a lambda is an anonymous function:
a function you define inline, without giving it a name.

Lambdas are useful when:

  • The function is small

  • The function isn’t used much

  • You want to keep related logic close to where it’s used

Example

main.cpp
int main() {  
  auto message = []() {  
    cout << "Hello World!\n";  
  };  
  
  message();  
  return 0;  
}

This just prints:
Hello World!

Breaking It Down 🕺

The Expression

[]() {
  cout << "Hello World!\n";
}```