LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 21 of 27

Lambda Expressions

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Lambda Expressions · Study material

Immediately invoked and constexpr lambdas

Calling a lambda right away is a neat way to initialise a const variable with logic that needs several statements. constexpr lambdas can build tables at compile time.

#include <array>
#include <iostream>
#include <string>

int main() {
    int marks = 78;
    // Immediately invoked lambda: initialise a const variable with complex logic
    const std::string grade = [&] {
        if (marks >= 90) return "A";
        if (marks >= 75) return "B";
        if (marks >= 60) return "C";
        return "F";
    }();

    // constexpr lambdas (C++17) run at compile time
    constexpr auto cube = [](int x) { return x * x * x; };
    constexpr std::array<int, 4> table = [] {
        std::array<int, 4> t{};
        for (int i = 0; i < 4; ++i) t[i] = (i + 1) * (i + 1) * (i + 1);
        return t;
    }();
    static_assert(cube(3) == 27 && table[3] == 64);
    std::cout << grade << ' ' << cube(5) << ' ' << table[2] << '\n';
    return 0;
}

Output

B 125 27

Capture explicitly, and think about lifetimes

// ✘ Dangling: the lambda outlives 'limit'
std::function<bool(int)> make_filter_bad() {
    int limit = 10;
    return [&limit](int x) { return x < limit; };     // limit is destroyed on return
}

// ✔ Copy what the lambda needs
std::function<bool(int)> make_filter(int limit) {
    return [limit](int x) { return x < limit; };
}

// ✔ Prefer named captures over [=] / [&] in long-lived lambdas
button.on_click([this, id = item.id] { open(id); });   // and make sure *this outlives the button

Lambdas with the STL

std::vector<Student> s = load();
int cutoff = 40;

auto passed  = std::count_if(s.begin(), s.end(), [cutoff](const Student& x) { return x.marks >= cutoff; });
auto topper  = std::max_element(s.begin(), s.end(), [](const auto& a, const auto& b) { return a.marks < b.marks; });
std::erase_if(s, [](const Student& x) { return x.name.empty(); });
std::sort(s.begin(), s.end(), [](const auto& a, const auto& b) { return std::tie(a.city, a.name) < std::tie(b.city, b.name); });

// Stateful lambda as a generator
int n = 0;
std::vector<int> ids(5);
std::generate(ids.begin(), ids.end(), [&n] { return 100 + n++; });   // 100 101 102 103 104

Lambda checklist

  • Keep lambdas short; give longer logic a named function.
  • Capture explicitly ([x, &y]) in code that lives long.
  • Capture by value when the lambda is stored or run later (threads, callbacks).
  • Use init captures to move resources in.
  • Use auto or templates to pass lambdas; std::function only for storage of mixed callables.
  • Mark lambdas constexpr when they are compile-time helpers.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links