cppadvanced10 minutes
Predict the Output of a Complex Recursive Lambda with State Captures in C++
Understand and predict the output of advanced C++ code involving recursive lambdas with mutable and reference state captures that manipulate shared variables and invoke themselves conditionally.
Challenge prompt
Analyze the following C++ code snippet that defines and invokes a recursive lambda function with both mutable and reference captures. Predict the exact output printed to the console when the program runs.
Guidance
- • Carefully track how the shared variables are modified throughout the recursive calls.
- • Understand how mutable lambdas allow changing captured variables and how references affect shared state across recursive calls.
- • Consider the order of operations and the stopping condition for recursion.
Hints
- • Remember that mutable lambdas make captured variables local copies that can be modified, unless captured by reference.
- • Recursive lambda calls share the same captured variables by reference, affecting subsequent calls.
- • Trace the changes step-by-step and note how the printed output relates to the variable states.
Starter code
#include <iostream>
int main() {
int x = 1;
int y = 2;
auto recurse = [&](auto&& self, int n) mutable -> void {
if (n == 0) return;
x += y;
y += 1;
std::cout << x << "-" << y << " ";
self(self, n - 1);
};
recurse(recurse, 4);
return 0;
}Expected output
3-3 6-4 10-5 15-6
Core concepts
recursive lambda functionsmutable lambda capturesreference capturesstate mutation across recursion
Challenge a Friend
Send this duel to someone else and see if they can solve it.