Modern C++: Lambdas
In this C++ lesson, we will study Lambdas through small executable cases. First we will make the normal result clear; then inspect data flow, ownership, failure behavior, and the caller contract before adding framework or infrastructure complexity.
Professional code is readable under change. A future developer should be able to identify which input is trusted, who may update state, where I/O happens, and how an expected error reaches a caller without reconstructing the whole application.
What You Will Build
Five focused C++ programs for Lambdas. Each has a visible result, an explicit contract, and a next change to test so the lesson becomes reusable knowledge rather than passive reading.
Example 1: Return a typed value
Let’s isolate one Modern C++ rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C++
#include <iostream>
int square(int value) { return value * value; }
int main() { std::cout << square(7) << "\n"; }Expected Result
49
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 2: Use an STL container
Let’s isolate one Modern C++ rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C++
#include <iostream>
#include <vector>
int main() { std::vector<int> values{2, 3, 4}; int total = 0;
for (int value : values) total += value; std::cout << total << "\n"; }Expected Result
9
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 3: Model ownership with RAII
Let’s isolate one Modern C++ rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C++
#include <iostream>
#include <memory>
int main() { auto value = std::make_unique<int>(42);
std::cout << *value << "\n"; }Expected Result
42
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 4: Use a generic function
Let’s isolate one Modern C++ rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C++
#include <iostream>
template <typename T> T larger(T left, T right) { return left > right ? left : right; }
int main() { std::cout << larger(4, 9) << "\n"; }Expected Result
9
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 5: Handle an expected error
Let’s isolate one Modern C++ rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C++
#include <iostream>
#include <stdexcept>
int main() { try { throw std::runtime_error("missing value"); }
catch (const std::exception& error) { std::cout << error.what() << "\n"; } }Expected Result
missing value
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 6: Make the input visible
Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Replace the sample value with one from your own notes, predict the result, and then run it.
Example 7: Guard an empty boundary
A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.
Example 8: Keep the transformation pure
This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.
Example 9: Make a branch deliberate
Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Change the boundary value by one and explain exactly which branch becomes active.
Example 10: Use a collection without hidden mutation
Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Add one more item and predict the derived result before executing the code.
Example 11: Return a named outcome
A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Rename the outcome in your own words while preserving the same success and failure rule.
Example 12: Trace a small loop
Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.
Example 13: Keep display at the edge
The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Change only the display text and verify that the underlying rule and result stay unchanged.
Example 14: Test the closest boundary
A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Try the lowest supported value and then one value just outside the accepted range.
Example 15: Write a tiny regression check
A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Modern C++: Lambdas.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C++
#include <iostream>
#include <string>
int main() {
const std::string lesson = "Modern C Lambdas";
std::cout << lesson << " | " << lesson.size() << "\n";
}Expected Result
Modern C Lambdas | 16
Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.
Design Review and Worked Trace
Review Modern C++: Lambdas as a full trace: input, validation, calculation or side effect, output, and cleanup. State the normal result, then state the boundary behavior. If either is hard to explain, split the work into a smaller function with a narrower contract.
Keep secret values and privileged decisions outside display code. Authentication establishes an identity; authorization decides what that identity may do. Check both close to protected operations, and use intentional failure responses rather than leaking internal details or crashing generically.
- Run the normal input and record the exact result.
- Test an empty, malformed, or boundary input deliberately.
- Keep state, ownership, and side effects visible to the caller.
- Return a result or named failure that can be tested.
- Never log credentials, tokens, or sensitive input.
This discipline makes C++ code easier to review, safer to change, and more useful in production than a collection of untested syntax fragments.
Common Mistakes
- Skipping input validation because a local example happened to work.
- Hiding mutation, ownership, or failure behavior inside a convenient shortcut.
- Using a client-side display rule as the only protection for sensitive work.
- Copying code without changing an input to prove its contract.
