Practice mode C++

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.