Assuming standard headers and using namespace std, what does this C++ code print? int x = 1; auto byVal = () { return x; }; auto byRef = () { return x; }; x = 5; cout << byVal() << byRef();
Correct answer D. 15
Explanation
A by-value capture [x] copies x into the lambda when the lambda is created, so byVal keeps the value 1 even after x changes. A by-reference capture [&x] stores a reference, so byRef sees the current value 5 when it is called. Choose by-reference capture only when the variable will outlive the lambda.
Answer checked How we write and check questions
Discussion