1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M11 Lambdas
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
57Mins
47Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M11 Lambdas

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
57Mins
47Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Lambdas

Overview

If you want to sort a Vector of Players by their score, std::sort requires you to write a custom 'Comparator' function. In older C++, you had to scroll to the top of your file, write a standalone function, and then pass it in. This scattered your logic and made code unreadable.

Modern C++ (C++11) introduced Lambda Expressions. A Lambda is an 'Anonymous Function'—a highly compressed function that you write inline, exactly at the exact line of code where it is needed. They are heavily utilized in multi-threading, STL algorithms, and event-handling (like UI button clicks).

Syntax

cpp
#include <iostream>

int main() {
    // THE LAMBDA SYNTAX: [] (parameters) { body }
    
    // 1. We store the anonymous function inside an 'auto' variable
    auto sayHello = []() {
        std::cout << "Hello from the Lambda!\n";
    };
    
    // 2. We execute it just like a normal function!
    sayHello();
    
    // 3. Lambda with parameters and a return value
    auto add = [](int a, int b) {
        return a + b;
    };
    
    std::cout << "Sum: " << add(5, 5) << "\n";
    
    return 0;
}

Common Pitfalls

  • The Capture Clause Trap. Unlike normal functions, Lambdas are physically created inside other functions (like inside main()). However, by default, a Lambda is mathematically BLIND to the variables around it. If you try to use a local main() variable inside the lambda body, it will fail to compile. You must 'Capture' the variables using the [ ] brackets.

Interview Questions

What is the specific difference between [&] and [=] in a Lambda's Capture Clause?

The Capture Clause dictates how the Lambda imports external variables. [&] imports every single local variable by Reference, allowing the Lambda to physically mutate the original variables. [=] imports every variable by Value (a read-only copy), physically blocking the Lambda from altering the external state.

Real-World Example

Using a Lambda directly inside std::count_if to count how many numbers are perfectly even, completely bypassing the need for a messy external function.

example
cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
    
    // The Lambda is written instantly inline!
    // It returns true if the number is even.
    int evens = std::count_if(numbers.begin(), numbers.end(), [](int n) {
        return (n % 2) == 0;
    });
    
    std::cout << "Even numbers found: " << evens << "\n"; // 3
    return 0;
}

Check Your Knowledge

Test your understanding of Lambdas with these quick questions.

Question 1

If a Lambda requires the ability to physically mutate a local variable that exists outside of its scope, what must be placed inside the Capture Clause `[ ]`?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Lambdas

Overview

If you want to sort a Vector of Players by their score, std::sort requires you to write a custom 'Comparator' function. In older C++, you had to scroll to the top of your file, write a standalone function, and then pass it in. This scattered your logic and made code unreadable.

Modern C++ (C++11) introduced Lambda Expressions. A Lambda is an 'Anonymous Function'—a highly compressed function that you write inline, exactly at the exact line of code where it is needed. They are heavily utilized in multi-threading, STL algorithms, and event-handling (like UI button clicks).

Syntax

cpp
#include <iostream>

int main() {
    // THE LAMBDA SYNTAX: [] (parameters) { body }
    
    // 1. We store the anonymous function inside an 'auto' variable
    auto sayHello = []() {
        std::cout << "Hello from the Lambda!\n";
    };
    
    // 2. We execute it just like a normal function!
    sayHello();
    
    // 3. Lambda with parameters and a return value
    auto add = [](int a, int b) {
        return a + b;
    };
    
    std::cout << "Sum: " << add(5, 5) << "\n";
    
    return 0;
}

Common Pitfalls

  • The Capture Clause Trap. Unlike normal functions, Lambdas are physically created inside other functions (like inside main()). However, by default, a Lambda is mathematically BLIND to the variables around it. If you try to use a local main() variable inside the lambda body, it will fail to compile. You must 'Capture' the variables using the [ ] brackets.

Interview Questions

What is the specific difference between [&] and [=] in a Lambda's Capture Clause?

The Capture Clause dictates how the Lambda imports external variables. [&] imports every single local variable by Reference, allowing the Lambda to physically mutate the original variables. [=] imports every variable by Value (a read-only copy), physically blocking the Lambda from altering the external state.

Real-World Example

Using a Lambda directly inside std::count_if to count how many numbers are perfectly even, completely bypassing the need for a messy external function.

example
cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
    
    // The Lambda is written instantly inline!
    // It returns true if the number is even.
    int evens = std::count_if(numbers.begin(), numbers.end(), [](int n) {
        return (n % 2) == 0;
    });
    
    std::cout << "Even numbers found: " << evens << "\n"; // 3
    return 0;
}

Check Your Knowledge

Test your understanding of Lambdas with these quick questions.

Question 1

If a Lambda requires the ability to physically mutate a local variable that exists outside of its scope, what must be placed inside the Capture Clause `[ ]`?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A