Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Management

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Templates C++ Files C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Projects

C++ Projects

C++ How Tos

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ Lambda Functions


Lambda Functions

A lambda function is a small, anonymous function you can write directly in your code. It's useful when you need a quick function without naming it or declaring it separately.

Think of it as a "mini function on the fly."

Syntax

[capture] (parameters) { code };

Don't worry: We'll explain what capture means later. For now, let's just use an empty pair of brackets.


Basic Lambda Example

Here, message holds a lambda function that prints a message to the screen:

Example

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

  message();
  return 0;
}

Result:

Hello World!
Try it Yourself »

Lambda with Parameters

You can pass values into a lambda just like a regular function:

#include <iostream>
using namespace std;

int main() {
  auto add = [](int a, int b) {
    return a + b;
  };

  cout << add(3, 4);
  return 0;
}

Result:

7
Try it Yourself »

Passing Lambdas to Functions

You can also pass a lambda function as an argument to another function.

This is useful when you want to tell a function what to do, not just what data to use.

In the example below, we send a small lambda function to another function, which then runs it twice:

#include <iostream>
#include <functional> // Needed for std::function
using namespace std;

// A function that takes another function as parameter
void myFunction(function<void()> func) {
  func();
  func();
}

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

  myFunction(message);
  return 0;
}

Result:

Hello World!
Hello World!
Try it Yourself »

Note that you must include the <functional> library for this example to work.


Using Lambdas in Loops

You can define and use a lambda function inside a loop, which are great for quick actions:

#include <iostream>
using namespace std;

int main() {
  for (int i = 1; i <= 3; i++) {
    auto show = [i]() {
      cout << "Number: " << i << "\n";
    };
    show();
  }
  return 0;
}

Result:

Number: 1
Number: 2
Number: 3
Try it Yourself »

Capture Clause [] (Optional)

You can use the [ ] brackets to give a lambda access to variables outside of it.

This is called the capture clause.

In this example, the lambda captures the variable x by value (a copy):

int main() {
  int x = 10;
  auto show = [x]() {
    cout << x;
  };

  show();
  return 0;
}

Result:

10
Try it Yourself »

Note: The lambda uses a copy of x. If you change x after defining the lambda, it won't affect the value inside the lambda.

Note: You can also use [&] to capture by reference.


Capture by Reference

If you want the lambda to use the latest value of a variable (not just a copy), you can use [&] to capture it by reference.

This means the lambda will work with the original variable, not a separate copy:

int main() {
  int x = 10;

  auto show = [&x]() {
    cout << x;
  };

  x = 20;  // Change x after the lambda is created

  show();
  return 0;
}

Result:

20
Try it Yourself »

Why? The lambda sees the original x variable, so when you change x, the lambda uses the updated value.


Regular Functions vs Lambda Functions

Both regular functions and lambda functions let you group code and run it later, but they are used in slightly different situations.

Use a regular function when:

  • You plan to reuse the function in multiple places
  • You want to give the function a clear, meaningful name
  • The logic is long or complex

Use a lambda function when:

  • You only need the function once
  • The code is short and simple
  • You want to pass a quick function into another function

Both of these examples do the same thing. They return the sum of two numbers:

Regular Function

int add(int a, int b) {
  return a + b;
}

Lambda Function

auto add = [](int a, int b) {
  return a + b;
};

Note: The lambda version is great when you don't need to reuse the function later. It's quick and works well inside blocks or as arguments to other functions.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.