---
id: cpp-functions-lambda
title: "C++ Lambda Functions"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["anonymous function", "capture clause", "capture by value vs reference", "C++ 람다 함수"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["cpp", "programming-language", "w3schools", "functions", "lambda"]
raw_sources: ["https://www.w3schools.com/cpp/cpp_functions_lambda.asp"]
applied_in: []
github_commit: ""
---

# [[CPP Lambda Functions]]

## 🎯 한 줄 통찰 (One-line insight)
The capture clause's TWO forms — `[x]` (by value, a frozen COPY at the moment of creation) versus `[&x]` (by reference, always the LATEST value) — produce genuinely different output for the identical-looking code: the same `show()` lambda prints `10` in one version and `20` in the other, purely because `x` was changed to 20 AFTER the lambda was defined — meaning the capture-clause choice determines whether a lambda is a snapshot of the past or a live window into the present. [S1]

## 🧠 핵심 개념 (Core concepts)
- **Lambda function** — `[capture](parameters) { code };` — an anonymous, throwaway function written inline, with no separate name/declaration required. [S1]
- **`auto` + lambda** — a lambda is typically stored via `auto varName = [...]() {...};` then called like a normal function (`varName();`). [S1]
- **Capture by value (`[x]`)** — the lambda gets a COPY of `x` frozen at creation time; later changes to the outer `x` don't affect the lambda's copy. [S1]
- **Capture by reference (`[&x]`)** — the lambda uses the ORIGINAL `x`; it always sees the latest value, even changes made AFTER the lambda was defined. [S1]
- **Passing a lambda as an argument** — requires `#include <functional>` and a `function<returnType(paramTypes)>` parameter type in the RECEIVING function. [S1]
- **Regular function vs. lambda** — use a regular function when reused often, needs a clear name, or logic is long; use a lambda for one-off, short, throwaway logic or when passing behavior into another function. [S1]

## 📖 세부 내용 (Details)
- Basic no-parameter lambda: `auto message = []() { cout << "Hello World!\n"; }; message();`. [S1]
- Lambda with parameters: `auto add = [](int a, int b) { return a + b; }; cout << add(3, 4); // 7`. [S1]
- Passing a lambda to another function: `void myFunction(function<void()> func) { func(); func(); } auto message = []() { cout << "Hello World!\n"; }; myFunction(message);` — requires `#include <functional>`. [S1]
- Capture by value freezes the value at creation: `int x = 10; auto show = [x]() { cout << x; }; show(); // 10, even if x changes afterward`. [S1]
- Capture by reference sees the LATEST value: `int x = 10; auto show = [&x]() { cout << x; }; x = 20; show(); // 20 — reflects the change made after the lambda was created`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **캡처 방식에 따라 동일한 코드가 다른 결과를 냄**: [x]로 값 캡처하면 람다 생성 시점의 x 값이 고정되지만, [&x]로 참조 캡처하면 이후 x가 바뀐 값을 그대로 반영한다는 점이 동일한 구조의 두 예제(10 vs 20 출력)로 직접 대비되어 증명됨. [S1]

## 🛠️ 적용 사례 (Applied in summary)
반복문 안에서 매 순회마다 다른 값을 캡처하는 람다를 즉석에서 정의해 사용하는 패턴(`for (int i = 1; i <= 3; i++) { auto show = [i]() {...}; show(); }`)이 원문에서 직접 실전 활용 사례로 제시됨. [S1]

## 💻 코드 패턴 (Code patterns)
Capture by value vs. capture by reference producing different output from identical-looking code (C++):
```cpp
int x = 10;
auto showCopy = [x]() { cout << x; };   // captures a frozen copy
auto showRef = [&x]() { cout << x; };   // captures the live variable
x = 20;
showCopy(); // 10 (unaffected by the later change)
showRef();  // 20 (reflects the latest value)
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[C++ Tutorial]]
- **관련 개념:** [[CPP Functions Recursion]], [[CPP References]], [[CPP OOP]]
- **참조 맥락:** 함수 섹션 마지막 — 객체지향 프로그래밍 기초(OOP Basics) 섹션으로 이어짐.

## 📚 출처 (Sources)
- [S1] W3Schools — C++ Lambda Functions — https://www.w3schools.com/cpp/cpp_functions_lambda.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ Lambda Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
