ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS

What is printed (C++17)?

What is printed (C++17)?
int main() {
    int x = 0;
    auto f = [x]() mutable { return ++x; };
    f();
    auto g = f;
    f();
    cout << f() << g() << x;
}
  1. A. 330
  2. B. 323
  3. C. 220
  4. D. 320

Correct answer: D. 320

The lambda owns its own copy of x. After one call it holds 1, and g copies that state. f() then reaches 2 and 3, g() goes from 1 to 2, and the outer x is never touched (0). C++17 sequences the << operands left to right.

More OOP with C++ and Java questions

Exams that ask this topic