ProgrammingModerateProduct-company placement · C++

What is printed?

What is printed?
int main() {
    int x = 1;
    auto byVal = [x]  { return x; };
    auto byRef = [&x] { return x; };
    x = 5;
    cout << byVal() << byRef();
}
  1. A. 55
  2. B. 11
  3. C. 51
  4. D. 15

Correct answer: D. 15

A by-value capture copies x when the lambda is created (1); a by-reference capture reads the current value at call time (5).

More OOP with C++ and Java questions

Exams that ask this topic