본문 바로가기
Computing technics/C++

Lambda Functions

by 연구실5호 2025. 4. 25.

 

Simple Explanation:

outside the code (or in a separate file, class, etc.), without having to declare or define, inlining both the function declaration and implementation right where needed is provided as a convenience.

In C++, function definitions typically live outside while internal code simply calls them, requiring you to jump around the codebase to understand behavior. Lambdas, however, keep everything in one place, greatly improving readability.

Moreover, they require no name, can capture and use surrounding variables, and are highly economical for simple one-off operations!

 

1. Example Using Lambda Functions

Syntax: auto add = [](int x, int y){ … };

#include <iostream>

int main() {
    // 1) Define a lambda and assign it to add
    auto add = [](int x, int y) {
        return x + y;
    };

    // 2) Call the lambda
    std::cout << "C++: 2 + 3 = " << add(2, 3) << "\n";

    // 3) Immediately-invoked lambda (IIFE)
    std::cout << "C++: 4 * 5 = "
              << [](int a, int b){ return a * b; }(4, 5)
              << "\n";

    return 0;
}

 

2. Example Using Regular Functions

Compare this with the lambda example above to see how it differs.

#include <iostream>

// 1) Define named functions
int add(int x, int y) {
    return x + y;
}

int multiply(int a, int b) {
    return a * b;
}

int main() {
    std::cout << "C++: 2 + 3 = " << add(2, 3) << "\n";
    std::cout << "C++: 4 * 5 = " << multiply(4, 5) << "\n";
    return 0;
}
  • Regular functions require separate declarations and definitions (or at least one consolidated definition in a separate location).
  • They are invoked by their names when called.
  • Unlike lambdas, you need to navigate to the external definition to understand their behavior. The example is simple, but imagine this in thousands of lines of code.

 

3. Closure Support

Lambda functions support closures, allowing you to use surrounding variables in operations without adding extra parameters.

#include <iostream>

int main() {
    int factor = 5;

    // Capture factor by value so mul can use it internally
    auto mul = [factor](int x) {
        return x * factor;  // factor is accessible even though it's not a function parameter
    };

    std::cout << "3 * factor(5) = " << mul(3) << "\n";  // 15
    return 0;
}
  • [factor] means to 'capture a copy of the external factor variable into the lambda.'
  • When you call mul(3), it computes 3 * 5 internally.
  • In this way, a closure is a powerful feature that 'closes over' surrounding variables (environment) when the lambda is defined, allowing the function to use those values without extra parameters.

 

4. Equivalent Python Examples

1) Lambda Function Example

def main():
    # 1) Define a lambda and assign it to add
    add = lambda x, y: x + y

    # 2) Call the lambda
    print(f"Python: 2 + 3 = {add(2, 3)}")

    # 3) Immediately-invoked lambda (IIFE)
    print("Python: 4 * 5 =",
          (lambda a, b: a * b)(4, 5))

if __name__ == "__main__":
    main()

 

2) Regular Function Example

def add(x, y):
    return x + y

def multiply(a, b):
    return a * b

def main():
    print(f"Python: 2 + 3 = {add(2, 3)}")
    print(f"Python: 4 * 5 = {multiply(4, 5)}")

if __name__ == "__main__":
    main()

 

3) Closure Example

def make_multiplier(factor):
    # Return a lambda that captures factor as a closure
    return lambda x: x * factor

mul5 = make_multiplier(5)
print(mul5(3))  # 15

 

'Computing technics > C++' 카테고리의 다른 글

람다 함수 (lambda function)  (0) 2025.04.25
Delete 메모리 해제 (Malloc 에러)  (2) 2024.10.24