Lambdas with Return Values
Part of the Logic & Flow section of Coddy's C++ journey — lesson 44 of 56.
Lambda expressions become much more powerful when they can return values back to the calling code. Instead of just performing actions, lambdas can calculate results and pass them back, just like regular functions.
To specify a return type for a lambda, use the arrow syntax -> type after the parameter list:
auto multiply = [](int a, int b) -> int {
return a * b;
};
int result = multiply(4, 5); // result is 20The return type specification is optional when the compiler can deduce it automatically, but it's good practice to include it for clarity. You can store the returned value in a variable or use it directly in expressions.
This capability makes lambdas perfect for small calculations that you need to perform inline without creating separate functions. Whether you're computing mathematical operations, string manipulations, or simple data transformations, returning values from lambdas keeps your code concise and readable.
Challenge
EasyCreate a program that demonstrates lambda expressions with return values by building a mathematical calculator that performs calculations and stores the results. This challenge will test your understanding of how to define lambda expressions that return computed values back to the calling code.
The following inputs will be provided:
- Two double numbers
num1andnum2representing the operands - A character
operationrepresenting the mathematical operation to perform
Your program should:
- Create a lambda expression named
calculatethat takes two double parameters and a char parameter for the operation - The lambda should use the arrow syntax
-> doubleto specify that it returns a double value - Inside the lambda, use conditional logic to perform the appropriate operation based on the operation character and return the result
- Read the two numbers and operation character from input
- Call the lambda with the input values and store the returned result in a variable
- Print the result using the specified format
The operation character will be one of:
+for addition-for subtraction*for multiplication/for division
Use the following exact output format:
Result: [calculated_result]The lambda should be defined with the syntax [](double a, double b, char op) -> double { ... } where the arrow syntax explicitly specifies the return type. Inside the lambda, use if-else statements or a switch statement to determine which operation to perform based on the operation character, then return the calculated value. Store the lambda in a variable using auto, call it with the input parameters, and capture the returned value to print it.
Cheat sheet
Lambda expressions can return values using the arrow syntax -> type to specify the return type:
auto multiply = [](int a, int b) -> int {
return a * b;
};
int result = multiply(4, 5); // result is 20The return type specification is optional when the compiler can deduce it automatically, but it's good practice to include it for clarity. You can store the returned value in a variable or use it directly in expressions.
Try it yourself
#include <iostream>
using namespace std;
int main() {
// Read input
double num1, num2;
char operation;
cin >> num1 >> num2 >> operation;
// TODO: Write your code here
// Create a lambda expression named 'calculate' that takes two double parameters and a char parameter
// Use the arrow syntax -> double to specify return type
// Use conditional logic inside the lambda to perform the operation and return the result
// TODO: Call the lambda with input values and store the result
// Output the result
cout << "Result: " << result << endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency7Advanced Functions
Pass by ReferenceIntro Lambda ExpressionsLambdas with ParametersLambdas with Return ValuesIntroduction to RecursionRecursive FactorialLambda Sort2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items